potentially dumb question

Discuss Programming
Post Reply
worker201
guru
guru
Posts: 668
Joined: Sun Jun 13, 2004 6:38 pm
Location: Hawaii

potentially dumb question

Post by worker201 » Fri Feb 11, 2005 4:31 pm

Can I write a simple boolean 'if' statement (evaluating the answer to a yes/no question) in a shell script? Or do I need to use C for that?

caveman
programmer
programmer
Posts: 130
Joined: Sun Feb 09, 2003 1:08 pm
Location: Midrand Gauteng, South Africa

Post by caveman » Fri Feb 11, 2005 4:54 pm

hmm - just a quick reply 'afore I have to go.

Yes - do a "man bash" - it will give you all the options

A quick place to pick up some workable and nice examples are
the scripts in the rc.d or init.d directory under etc.

an "if" statement starts with an "if" an optional "else"
and is terminated by "fi" ....something like the following
if [ 1 = 1 ] then
statements
else
statements
fi

eg. from anacron in in the init.d directory
if [ -z "$1" ] ; then
map="auto_master"
else
map="$1"
fi

input from the terminal can be had by using "read" and assigning
it to a variable which can be used later.

Hope this puts you on the right track...

worker201
guru
guru
Posts: 668
Joined: Sun Jun 13, 2004 6:38 pm
Location: Hawaii

Post by worker201 » Fri Feb 11, 2005 6:50 pm

Groovy, gonna work with that next week. Thanks!

jaem
n00b
n00b
Posts: 3
Joined: Fri Oct 31, 2003 4:00 pm

Post by jaem » Sat Feb 12, 2005 3:26 pm

Browse Advanced Bash-Scripting Guide (downloadable as a pdf,...). One common error is forgetting to put a space after (resp. before) the [ (resp. ]). You also got one liners like

Code: Select all

[ 1 = 1 ] && echo "1 = 1"
[ 1 = 1 ] ||  echo "what? 1 != 1"
which are equivalent to "if ... statement", "iunless ... statement".

Note: a test in bash is just the return value of a program/builtin, with the convention 0=true. In bash [ ... ] is a builtin. But other shells (sh?) use /usr/bin/[ which is a link to /usr/bin/test.

Post Reply