exxon
exxon

Reputation: 87

bash sh differences, script conversion

I have this script that was written in bash

#!/bin/sh

# script makes grep directly on dmesg output
# looking  for  'USB disconnect'  phrase  if
# it  finds  it  then  machine  is  rebooted
# ver 1.2
clear

UNPLUG_MESSAGE="PLEASE UNPLUG THE USB STICK NOW"
echo $UNPLUG_MESSAGE && sleep 2

while true; do

USB_STATUS=`dmesg | tail -n 5 |  grep 'disconnect'`

  if [[ $USB_STATUS == *USB?disconnect* ]]
     then
        clear && echo "Rebooting... bye" 
    sleep 1 && sudo reboot

  elif [[ $USB_STATUS != *USB?disconnect* ]]
     then
        clear && echo "Please remove USB drive..."
        sleep 2
  fi
done

exit 0

After changing #!/bin/bash to #!/bin/sh, the script does not work any more - what should I change in this script?

I got errors like unknown operand USB?disconnect, ./reboot.sh: 16: ./reboot.sh: [[: not found, etc.

Upvotes: 0

Views: 417

Answers (1)

jmlemetayer
jmlemetayer

Reputation: 4952

On ubuntu sh is dash (you can run ls -l $(which sh) to see this).

In dash there is no [[ (double brackets) operator. You have to use the test builtin function or [ (single brackets) only.

You can replace:

if [[ $USB_STATUS == *USB?disconnect* ]]
...
elif [[ $USB_STATUS != *USB?disconnect* ]]

By:

if [ $(echo $USB_STATUS | grep -c "USB disconnect") != 0 ]
...
elif [ $(echo $USB_STATUS | grep -c "USB disconnect") = 0 ]

Upvotes: 4

Related Questions