shell脚本中的变量
当脚本中使用某个字符串较频繁并且字符串长度很长时就应该使用变量代替
使用条件语句时,常使用变量
1
2
3if [[ condition ]]; then
statements
fi引用某个命令的结果时,用变量替代
1
n=`wc -l 1.txt`
写和用户交互的脚本时,变量也是必不可少的 read -p “lnput anumber:” n; echo $n 如果没写这个n,可以直接使用 $REPLY
内置变量 $0,$1,$2… $0表示脚本本身,$1第一个参数,$2第二个… $#表示参数个数
数学运算 a=1; b=2; c=(($a+$b)) 或者 $[$a+$b]
shell中的逻辑判断
格式一
1
2
3if [[ 条件 ]]; then
语句
fi格式二
1
2
3
4
5if [[ 条件 ]]; then
语句
else
语句
fi格式三
1
2
3
4
5
6
7if [[ ... ]]; then
...
elif
...
else
...
fi逻辑判断表达式:
1
2
3
4
5
6
7if [[ $a -gt $b ]];
if [[ $a -lt 5 ]];
if [[ $b -eq 10 ]];等
); -lt(<); -ge(>=); -le(<=); -eq(==); -ne(!=) 注意到处都是空格
可以使用 && || 结合多个条件
if [[ $a -gt 5 ]]&&[[ $a -lt 10 ]]; then 逻辑并
if [[ $b -gt 5 ]]||[[ $b -lt 3 ]]; then 逻辑或
if判断文件、目录属性
1 | [[ -f file ]] 判断是否是普通文件、且存在 |
if判断的一些特殊用法
1 | if [[ -z "$a" ]] |
- []中不能使用>、<、==、!=、>=、<=这样的符号,一个 = 是赋值
- -z 或者 -n都不能作用在文件上,只能作用在变量上
- ! -z EQUATE -n 、! -n EQUATE -z
- if grep -q ‘123’ 1.txt; then 取反为:if ! grep -q ‘123’ 1.txt; then
case判断
case格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15case VARIABLE NAME in
value1)
COMMAND
;;
value2)
COMMAND
;;
*)
COMMAND
;;
esac
在case程序中,可以在条件中使用 | ,表示或的意思,比如
2|3)
COMMAND
;;示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41!/bin/bash
read -p "Please input a number: " n
if [[ -z "$n" ]]; then
echo "Please input a number."
exit 1
if
n1=`echo $n | sed 's/[0-9]//g'`
if [[ ! -z $n1 ]]; then # [[ -n $1 ]]
echo 'Please input a number.'
exit 1
elfi [[ $n -lt 0 ]] || [[ $n -gt 100 ]]; then
echo 'The number range is 0-100.'
exit 1
fi
fi [[ $n -ge 0 ]] && [[ $n -lt 60 ]]; then
tag=1
elfi [[ $n -ge 60 ]] && [[ $n -lt 80 ]]; then
tag=2
elfi [[ $n -ge 80 ]] && [[ $n -lt 90 ]]; then
tag=3
elfi [[ $n -ge 90 ]] && [[ $n -le 100 ]]; then
tag=4
else
tag=0
fi
case $tag in
1)
echo 'not ok'
;;
2)
echo 'ok'
;;
3|4)
echo 'very ok'
;;
0)
echo 'The number range is 0-100'
;;
esac