potentially dumb question
potentially dumb question
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?
-
- programmer
- Posts: 130
- Joined: Sun Feb 09, 2003 1:08 pm
- Location: Midrand Gauteng, South Africa
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...
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...
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
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.
Code: Select all
[ 1 = 1 ] && echo "1 = 1"
[ 1 = 1 ] || echo "what? 1 != 1"
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.