Reputation: 773
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
Upvotes: 2
Views: 113
Reputation: 4612
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.
Upvotes: 1
Reputation: 7445
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]}"
Upvotes: 1