Computing.Net > Forums > Programming > BASH `echo $?` in if statement

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

BASH `echo $?` in if statement

Reply to Message Icon

Name: Kenshin
Date: July 4, 2002 at 06:27:16 Pacific
Comment:

#!/bin/bash
# auto-cd: script for lazy people
#
eject
sleep 5
eject -t
mount /cdrom # you might have to change this if you don't use SuSE
#Here comes the funny part
if ( `echo $?` -eq 0)
then
konqueror /cdrom #change this to nautilus if you use gnome
else
exit 1
fi

#Now just create a link on your desktop
#to this file and you'll be 1 click away from the contents of your cd

##NOTE: if you execute it, you'll get a auto-cd: 0: command not found
## My question is, why the function does not work?
## The `echo $?` should test if the mount command was successful. If it
## was successful, then it should open your file browser and display the contents
## of the cd, if mount was unsuccesful, then it should exit without calling konqueror
## or nautilus.



Sponsored Link
Ads by Google

Response Number 1
Name: Tom
Date: July 4, 2002 at 08:06:53 Pacific
Reply:

Why do you need to echo it?
if($? == 0)


0

Response Number 2
Name: ddddummy
Date: July 7, 2002 at 14:02:33 Pacific
Reply:


>> if ( `echo $?` -eq 0)
ahemm...
sure both of you do not want to use square brackets? ;-)

all these are possible:
if [ `echo $?` -eq 0 ] ...
if [ $? -eq 0 ] ...
if [ `echo $?` == 0 ] ...
if [ $? == 0 ] ...

as == and -eq are the same, and the contents of an environment or special variable is certainly equal to its output via echo.. but the [] brackets, or more specifically, the '[' (begin boolean evaluation) shell builtin and the corresponding ']' end-of-evaluation marker, are necessary because elsewhere the -eq and == operators are not valid.

in fact, [ is a perfectly normal shell builtin, you could also write this:

[ $? == 0 ] && konqueror /cdrom || exit 1

which boils down the if block to one line.



0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: BASH `echo $?` in if statement

Multiple commands in if statement www.computing.net/answers/programming/multiple-commands-in-if-statement/18063.html

DOS - result of command used in if statement www.computing.net/answers/programming/dos-result-of-command-used-in-if-statement/19202.html

Wildcards in if statement www.computing.net/answers/programming/wildcards-in-if-statement/10769.html