if [ $# -lt 3 ]
then
printf "%b" "Error. Not enough arguments.\n"
printf "%b" "usage: myscript file1 op file2\n"
exit 1
fi
Decisions
if (( b == 12 )); then echo 'foo'; else echo 'bar'; fi
Could put on separate lines and omit the semicolons
Decisions
What's the difference between square and round brackets?
Round brackets are strictly for numeric expressions.
Square brackets can be used for file characteristics
Testing for file characteristics
Make sure file exists
if [ -e "foo.txt" ]
See table 6-2 to see other unary file characteristic operators.
All the file test conditions include an implicit test for existence, so you don’t need to test if a file exists and is readable. It won’t be readable if it doesn’t exist.
Test values of strings
Maybe you got from user input?
if [ -n "$VAR" ]
The -n checks to see if var is not null.
Use a -z to see if a string is null.
Should always double quote the string when testing.
Bash comparison operators
These only apply if you are using the [ ] notation.
i=0
while (( i < 5 )); do echo $i; ((i++)); done
while read foo; do echo "i am $foo"; done
For the above read loop, you could also call it like:
./bar.sh < cows.txt #assuming the script was named bar.sh
While loop reading from a file
while read foo; do echo "i am $foo"; done < cows.txt
or
while read foo
do
echo "$foo is a single line from that file"
done < cows.txt
For loops
for (( i=0 ; i < 10 ; i++ )) ; do echo $i ; done
for i in $(seq 1 10); do echo $i; done
for i in {1..10}; do echo $i; done
for name in tom fred stan; do echo $name; done