I have the following bash script which works fine until I get to number 9 (/dev/sdj) where it does not produce the expected output.
hdd1="$(sudo fdisk -l | grep "Disk /dev/sd" | awk '{print$2}' | sed 's/://g')"
counter=0
function check {
i="0"
while [ $i == "0" ]
do
hdd2="$(sudo fdisk -l | grep "Disk /dev/sd" | awk '{print$2}' | sed 's/://g')"
hdd1_count=$(echo "$hdd1" | wc -l)
hdd2_count=$(echo "$hdd2" | wc -l)
# Check if added or removed
if [[ "$hdd1_count" < "$hdd2_count" ]]
then
echo -e "\e[32mHDD ADDED\e[0m"
counter=$((counter+1))
echo "Total HDD: $counter"
echo "HDD1: $hdd1"
echo "HDD2: $hdd2"
hdd1=$hdd2
echo "HDD1 is now: $hdd1"
# Get last disk in var
last=$(echo "${hdd1##*$'\n'}")
echo "LAST: $last"
elif [[ "$hdd1_count" > "$hdd2_count" ]]
then
echo -e "\e[32mHDD REMOVED\e[0m"
counter=$((counter-1))
echo "Total HDD: $counter"
echo "HDD1: $hdd1"
echo "HDD2: $hdd2"
hdd1=$hdd2
echo "HDD1 is now: $hdd1"
# Get last disk in var
last=$(echo "${hdd1##*$'\n'}")
echo "LAST: $last"
fi
done
}
check
Here is the output:
HDD ADDED
Total HDD: 1
HDD1: /dev/sda
HDD2: /dev/sda
/dev/sdb
HDD1 is now: /dev/sda
/dev/sdb
LAST: /dev/sdb
This works until /dev/sdi as followed:
HDD ADDED
Total HDD: 8
HDD1: /dev/sda
/dev/sdb
/dev/sdc
/dev/sdd
/dev/sde
/dev/sdf
/dev/sdg
/dev/sdh
HDD2: /dev/sda
/dev/sdb
/dev/sdc
/dev/sdd
/dev/sde
/dev/sdf
/dev/sdg
/dev/sdh
/dev/sdi
HDD1 is now: /dev/sda
/dev/sdb
/dev/sdc
/dev/sdd
/dev/sde
/dev/sdf
/dev/sdg
/dev/sdh
/dev/sdi
LAST: /dev/sdi
Then I get to insert disk 9 and the output changes but I cannot find the problem why it isn't going on like expected. Here is the output:
HDD REMOVED
Total HDD: 7
HDD1: /dev/sda
/dev/sdb
/dev/sdc
/dev/sdd
/dev/sde
/dev/sdf
/dev/sdg
/dev/sdh
/dev/sdi
HDD2: /dev/sda
/dev/sdb
/dev/sdc
/dev/sdd
/dev/sde
/dev/sdf
/dev/sdg
/dev/sdh
/dev/sdi
/dev/sdj
HDD1 is now: /dev/sda
/dev/sdb
/dev/sdc
/dev/sdd
/dev/sde
/dev/sdf
/dev/sdg
/dev/sdh
/dev/sdi
/dev/sdj
LAST: /dev/sdj
I have changed the script now for 2 days in a row but I keep getting the same result. Can someone spot the problem?
EDIT:
-lt and -gt did the trick, thanks!
<being lexicographic comparison, not arithmetic comparison.10 < 9because1 < 9. You're probably looking for-lt. Also, consider using arrays instead of whatever it is you're doing now.fdiskoutput, you can simply iterate through/dev/sd[a-z](e.g.for disk in /dev/sd[a-z]; do .. done).