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 
6
  • Shouldnt it be "$x" == "0" instead of =? Commented Apr 18, 2019 at 4:31
  • @NirupIyer stackoverflow.com/a/2237103/2064607 I referred to this while writing code. Commented Apr 18, 2019 at 4: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' Commented Apr 18, 2019 at 4: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 echoing the value of x just before first if condition (which seems redundant) Commented Apr 18, 2019 at 4: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 Commented Apr 18, 2019 at 4:53

2 Answers 2

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]}" 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.