LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash script error near 'else' ? (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-near-else-281239/)

nutthick 01-23-2005 11:19 AM

bash script error near 'else' ?
 
I've been working on my first script below:

#
# Script to mount and list everything on a USB drive. The drive is unmounted at the end
#

echo "Mounting USB drive"
mount /mnt/usb

# Did the previous command throw up anything?
if [$? -gt 0] then
# There was a problem check it out
if [$? -eq 32] then
# Drive is already mounted, just display it's contents and unmount
ls /mnt/usb -al
umount /mnt/usb

echo "Unmounting USB drive"
else
# Some other problem, assume nothing connected
echo "There are currently no compatible USB drives connected"
fi

exit 1
else
# Drive mounted without problem, display it's contents and unmount it
ls /mnt/usb -al
umount /mnt/usb

echo "Unmounting USB drive"
fi

exit 0


but when I run it I get the following error:

line 17: syntax error near unexpected token 'else'

As far as I can see everything is OK, does any know what the problem is?

meblost 01-23-2005 11:34 AM

Try putting the thens on their own line and adding a space between each bracket and what it encloses. ie [ $? -eq 32 ] instead of [$? -eq 32].

nutthick 01-23-2005 11:45 AM

Thanks meblost, 100% correct. Those changes sorted it out perfectly. Just one more question, do you know of any way to suppress the OS output. When a drive isn't connected I get the bash line

mount: /dev/sdb1 is not a valid block device

before my line about no compatible drives connected. Ideally I would just like my output to be displayed.

Thanks for you help so far

LasseW 01-23-2005 02:53 PM

There's another error in the script: the first $? is the return code from the mount command. The if statement will execute a test command and the second $? is the return code from that command, probably not what you intended. To test the same rc in both ifs, assign it to a variable immediatley after mount:

RC=$?

Then use the variable in both if statements.

jonaskoelker 01-23-2005 03:37 PM

for redirection, try '(some command) > /dev/null' or '(same command) 2> /dev/null'; I'm guessing you want the second.

nutthick 01-23-2005 03:41 PM

LasseW - I'd just discovered the error when I read your post. Thanks for the reply, I didn't realise that an if statement would affect the $? value.

jonaskoelker - I'm just compiling at the moment, but I'll give it a try if this thing ever finishes!


All times are GMT -5. The time now is 01:31 AM.