第17篇 shell编程基础(2)

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

转载于:https://www.cnblogs.com/zhouqingda/p/5205613.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值