- 重定向输入和输出
- 输出重定向
bash shell用大于号(>)来完成这项功能:command > outputfile
如果不想覆盖文件原有内容,而是想要将命令的输出追加到已有文件中,比如你正 在创建一个记录系统上某个操作的日志文件。在这种情况下,可以用双大于号(>>)来追加数据。
- 输入重定向
输入重定向符号是小于号(<): command < inputfile
(vent) szbddeMacBook-Pro-3:shell $ wc < test6
3 16 99
wc命令可以对对数据中的文本进行计数。默认情况下,它会输出3个值:
文本的行数
文本的词数
文本的字节数
2.退出脚本
查看Linux退出状态码:echo $?
3.数值比较
4.字符串比较
5.文件比较
6.双括号命令符号
双圆括号:可以是任意的数学赋值或比较表达式
双方括号:针对字符串的高级特性
7.case命令
#!/bin/bash
case $USER in
v_suxue | barbara)
echo "Welcome, $USER"
echo "Please enjoy your visit";;
testing)
echo "Special testing account";;
jessica)
echo "Do not forget to log off when you're done";;
*)
echo "Sorry, you are not allowed here";;
esac
# 打印
Welcome, v_suxue
Please enjoy your visit
8.更改字段分隔符
- 空格
- 制表符
- 换行符
9.break命令
- 跳出单个循环
#!/bin/bash
for var1 in 1 2 3 4 5 6 7 8 9 10
do
if [ $var1 -eq 5 ]
then
break
fi
echo "Iteration number: $var1"
done
echo "The for loop is completed"
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
The for loop is completed
- 跳出内部循环
#!/bin/bash
for (( a = 1; a < 4; a++))
do
echo "Outer loop: $a"
for (( b = 1; b < 100; b++ ))
do
if [ $b -eq 5 ]
then
break
fi
echo " Inner loop: $b"
done
done
Outer loop: 1
Inner loop: 1
Inner loop: 2
Inner loop: 3
Inner loop: 4
Outer loop: 2
Inner loop: 1
Inner loop: 2
Inner loop: 3
Inner loop: 4
Outer loop: 3
Inner loop: 1
Inner loop: 2
Inner loop: 3
Inner loop: 4
- 跳出外部循环
停止外部循环,break命令接受单个命令行参数值:break n
默认情况下,n为1,表明跳出的是当前的循环。如果你将n设为2,break命令就会停止下一级的外部循环。
#!/bin/bash
for (( a = 1; a < 4; a++))
do
echo "Outer loop: $a"
for (( b = 1; b < 100; b++ ))
do
if [ $b -gt 4 ]
then
break 2
fi
echo " Inner loop: $b"
done
done
Outer loop: 1
Inner loop: 1
Inner loop: 2
Inner loop: 3
Inner loop: 4
10.continue命令
#!/bin/bash
for(( var1 = 1; var1 < 15; var1++ ))
do
if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
then
continue
fi
echo "Iteration number: $var1"
done
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
Iteration number: 10
Iteration number: 11
Iteration number: 12
Iteration number: 13
#!/bin/bash
for(( a = 1; a <= 5; a++ ))
do
echo "Iteration $a:"
for (( b = 1; b < 3; b++ ))
do
if [ $a -gt 2 ] && [ $a -lt 4 ]
then
continue 2
fi
var3=$[ $a * $b ]
echo " The result of $a * $b is $var3"
done
done
Iteration 1:
The result of 1 * 1 is 1
The result of 1 * 2 is 2
Iteration 2:
The result of 2 * 1 is 2
The result of 2 * 2 is 4
Iteration 3:
Iteration 4:
The result of 4 * 1 is 4
The result of 4 * 2 is 8
Iteration 5:
The result of 5 * 1 is 5
The result of 5 * 2 is 10