脚本中括号组合的说明
[转自](https://www.shiyanlou.com/courses/944)- ()会开启一个新的子shell,
- {}不会开启一个新的子shell
- (())常用于算术运算比较,[[]]常用于字符串的比较.
- $()返回括号中命令执行的结果
- $(())返回的结果是括号中表达式值
- ${ }参数替换与扩展
1.if流程控制示例
#!/bin/bash
echo hello; echo there
filename=ttt.sh
if [ -e "$filename" ]; then # 注意: "if"和"then"需要分隔,
#-e用于判断文件是否存在
echo "File $filename exists."; cp $filename $filename.bak
else
echo "File $filename not found."; touch $filename
fi; echo "File test complete."
解释说明
上面脚本使用了一个if分支判断一个文件是否存在,如果文件存在打印相关信息并将该文件备份;如果不存在打印相关信息并创建一个新的文件。最后将输出"测试完成"。 注意空格
if-elif-else 语法格式
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
if 结合 test 使用
#!/bin/bash
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
echo 'Two numbers are equal!'
else
echo 'The two numbers are not equal!'
fi
for循环,break和continue跳出循环
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
#示例1
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
#示例2,将 /etc 下目录的文件名循环出来。
for file in `ls /etc`
或
for file in $(ls /etc)
while语句循环
while condition
do
command
done
#示例
int=1
while(( $int<=5 ))
do
echo $int
let "int++"
done
#如果int小于等于5,那么条件返回真。int从1开始,每次循环处理时,int加1。运行上述脚本,
#返回数字1到5,然后终止。
#使用了 Bash let 命令,它用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量
until循环,至少执行一次
until condition
do
command
done
case语法及示例
case 值 in
模式1)
command1
command2
...
commandN
;;
模式2)
command1
command2
...
commandN
;;
esac
#示例,例子中,脚本进入死循环直至用户输入数字大于5.跳出这个循环
#!/bin/bash
while :
do
echo -n "Enter a number between 1 and 5:"
read aNum
case $aNum in
1|2|3|4|5) echo "The number you entered is $aNum!"
;;
*) echo "The number you entered is not between 1 and 5! game over!"
break
;;
esac
done
2.case单串匹配
#!/bin/bash
varname=b
case "$varname" in
[a-z]) echo "abc";;
[0-9]) echo "123";;
esac
解释说明
上面脚本使用case语句,首先创建了一个变量初始化为b,然后使用case语句判断该变量的范围,并打印相关信息。
3.括号与数组
#!/bin/bash
a=123
( a=321; )
echo "$a"
#a的值为123而不是321,因为小括号将判断为局部变量
{ a=323; }
echo "$a"
#a的值为323而不是123,因为大括号将判断代码块,代码块;
#在其中声明的变量,对于脚本其他部分的代码来说还是可见的。
arr=(1 4 5 7 9 21) #初始化数组
echo ${arr[3]} #输出为7 从数组获取索引为3的数据
4.文件名扩展
#!/bin/bash
if [ ! -w 't.txt' ];
then
touch t.txt #创建t.txt文件
fi
echo 'test text' >> t.txt #在t.txt文件中直接内容
cp t.{txt,back} #将t.txt文件及内容复制一份另存为t.back
注意: 在大括号中,不允许有空白,除非这个空白被引用或转义