file=/etc/passwd
if [[ -e $file ]]
then
echo "Password file exists."
fi
Using the [[ ... ]] test construct, rather than [ ... ] can prevent many logic errors in scripts. For example, the &&, ||, <, and > operators work within a [[ ]] test, despite giving an error within a [ ] construct.
_____
Following an if, neither the test command nor the test brackets ( [ ] or [[ ]] ) are strictly necessary.
dir=/home/bozo
if cd "$dir" 2>/dev/null; then # "2>/dev/null" hides error message.
echo "Now in $dir."
else
echo "Can't change to $dir."
fi
_____
A condition within test brackets may stand alone without an if, when used in combination with a list construct.
var1=20; var2=22
[ "$var1" -ne "$var2" ] && echo "$var1 is not equal to $var2"
home=/home/bozo
[ -d "$home" ] || echo "$home directory does not exist."
_____
# arithmetic comparison:
if [ "$a" -ne "$b" ]
# Alternatively, the (( )) construct expands and evaluates an arithmetic expression.
# String comparision:
if [ "$a" != "$b" ]
_____
The * in case can be confusing. To resolve this, wrap the list in an extra set of delimiters when expanding it:
list=orange,apple,banana
case ,$list, in
*,orange,*) echo "The only fruit for which there is no Cockney slang.";;
esac
The expansion of $list now has a comma appended to each end, ensuring that every member of the list has a comma on both sides of it.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.