2

I am trying to find out whether disk is SSD or HDD using bash script.

logical_name="/dev/sda"
type="" 
disk=$(basename $logical_name)
x=`cat $filename | grep "${disk}" | awk '{print $2}'`
if [ ! -z "$x" ]
then
        if [ "$x" = "0" ]
        then
                type="SSD"
        fi  
        if [ "$x" = "1" ]
        then
                type="HDD"
        fi  
fi

echo $type

Value of x is correct, 0 or 1. But after comparison, it's not assigning any value to variable type. It prints as empty. Can anyone point out what am I doing wrong here?

More information:

$filename is a file that contains output of sudo lsblk -d -o name,rota

NAME ROTA
sda     1
sdd     1
sdc     0
gkr2d2
  • 693
  • 2
  • 9
  • 20
  • Shouldnt it be "$x" == "0" instead of =? – Nirup Iyer Apr 18 '19 at 04:31
  • @NirupIyer https://stackoverflow.com/a/2237103/2064607 I referred to this while writing code. – gkr2d2 Apr 18 '19 at 04:36
  • Though it's not a direct solution to your question, you could use `sed` to simplify this: `lsblk -d -o name,rota | sed -e 's/0$/SSD/g' -e 's/1$/HDD/g'` – Jebby Apr 18 '19 at 04:37
  • I don't see anything wrong here (despite there being some unnecessary checks). If `type` is empty at the end, that means the conditional has failed. Try `echo`ing the value of `x` just before first `if` condition (which seems redundant) – Anubis Apr 18 '19 at 04:41
  • Please run the script with `bash -x yourfile` and edit your post to include the debug log if the problem does not become immediately obvious – that other guy Apr 18 '19 at 04:53
  • Also see [How to use Shellcheck](http://github.com/koalaman/shellcheck), [How to debug a bash script?](http://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](http://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](http://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Apr 18 '19 at 11:59

2 Answers2

1

While I don't see any problem with the posted code, following would be a more simplified and maintainable version for doing the same.

DISK_NAMES=(SSD HDD)  # names are resolved by index

filename="in1.txt"
logical_name="/dev/sda"
disk="$(basename $logical_name)"
x="$(sed -n 's/'$disk' *\([0-9]*\)/\1/p' $filename)"
# check if $x is empty here, if required
echo "$x -> ${DISK_NAMES[$x]}"
Anubis
  • 6,995
  • 14
  • 56
  • 87
1

The lsblk command lets you specify a device, so you shouldn't have to grep through the lsblk output to find the device you're interested in. This also means you don't need the name column. Plus you can disable the header with -n, and the -r option (raw output) gets rid of the leading and trailing whitespace:

> hdtype() { lsblk -drno rota "$1" | sed 's/1/HDD/;s/0/SSD/'; }

> hdtype /dev/sda
HDD

As far as why your code isn't working, I'm not sure. It worked just fine in my bash terminal.

Mike Holt
  • 4,452
  • 1
  • 17
  • 24