shell study
1、Exit Status
If the command executed successfully (or true), the value of $? is zero. If the command failed for some reason, $? will contain a positive integer between 1 and 255, inclusive.A failed command usually returns 1.
2、Testing an Expression
The test command evaluates many kinds of expressions,from file properties to integers to strings.
1)file tests,A file’s existence can be tested with -e (or the nonstandard -a). The type of file can be checked with -f for a regular file, -d for a directory, and -h or -L for a symbolic link. for example:
test -f /etc/fstab ## true if a regular file
test -h /etc/rc.local ## true if a symbolic link
[ -x "$HOME/bin/hw" ] ## true if you can execute the file
[[ -s $HOME/bin/hw ]] ## true if the file exists and is not empty
2)Comparisons between integers use the -eq, -ne, -gt,-lt,-ge,and -le operators.
below is a example:
$ test 1 -eq 1
$ echo $?
3) String Tests,The = operator tests for equality, in other words,whether they are identical;
!= tests for inequality.The -z and -n operators return successfully if their arguments are empty or nonempty.
here ara some example:
test "$a" = "$b"
[ "$q" != "$b" ]
$ [ -z "" ]
$ echo $?
0 #判空
$ test -n ""
$ echo $?
1
3、[[ ... ]]: Evaluate an Expression
4、(( ... )): Evaluate an Arithmetic Expression
5、Conditional Execution
example:
read name
if [[ -z $name ]]
then
echo "No name entered" >&2
exit 1 ## Set a failed return code
fi
read number
if (( number > 10 ))
then
printf "%d is too big
" "$number" >&2
exit 1
else
printf "You entered %d
" "$number"
fi
6、Conditional Operators, && and ||
Lists containing the AND and OR conditional operators are evaluated from left to right. A
command following the AND operator (&&) is executed if the previous command is
successful. The part following the OR operator (||) is executed if the previous command
fails.
7、case
语法如下:
case WORD in
PATTERN) COMMANDS ;;
PATTERN) COMMANDS ;; ## optional
esac
8、Loop
1)while语法:
while <list>
do
<list>
done
实例:
n=1
while [ $n -le 10 ]
do
echo "$n"
n=$(( $n + 1 ))
done
2)util 很少用,跟while刚好相反(循环会条件fails),实例如下,
n=1
until [ $n -gt 10 ]
do
echo "$n"
n=$(( $n + 1 ))
done
3)for,实例:
for (( n=1; n<=10; ++n ))
do
echo "$n"
done
4)break
do
read x
[ -z "$x" ] && break
done
5)continue
for n in {1..9} ## See Brace expansion in Chapter 4
do
x=$RANDOM
[ $x -le 20000 ] && continue
echo "n=$n x=$x"
done