码迷,mamicode.com
首页 > 系统相关 > 详细

第17篇 shell编程基础(2)

时间:2016-02-21 22:34:21      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

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\n" "$number" >&2
exit 1
else
printf "You entered %d\n" "$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

第17篇 shell编程基础(2)

标签:

原文地址:http://www.cnblogs.com/zhouqingda/p/5205613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!