Shell 流程控制
if else
- if
复制代码
1
2
3
4
5
6
7
if condition
then
command1
command2
...
commandN
fi
- if else
复制代码
1
2
3
4
5
6
7
8
9
if condition
then
command1
command2
...
commandN
else
command
fi
- if else-if else
复制代码
1
2
3
4
5
6
7
8
9
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
for 循环
复制代码
1
2
3
4
5
6
7
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
while 语句
复制代码
1
2
3
4
while condition
do
command
done
可以连续读取键盘的信息
复制代码
1
2
3
4
5
6
echo '按下 <CTRL-D> 退出'
echo -n '输入你最喜欢的电影名: '
while read FILM
do
echo "是的!$FILM 是一部好电影"
done
until 循环
复制代码
1
2
3
4
until condition
do
command
done
case 语句
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read aNum
case $aNum in
1)
echo '你选择了 1'
;;
2)
echo '你选择了 2'
;;
3)
echo '你选择了 3'
;;
4)
echo '你选择了 4'
;;
*)
echo '你没有输入 1 到 4 之间的数字'
;;
esac
Shell 函数
- 简单函数
复制代码
1
2
3
4
5
6
7
8
#!/bin/bash
helloFun(){
echo "hello world"
}
echo "-----函数开始执行-----"
helloFun
echo "-----函数执行完毕-----"
- 函数参数
复制代码
1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
funWithParam(){
echo "第一个参数为 $1 !"
echo "第二个参数为 $2 !"
echo "第十个参数为 ${10} !"
echo "第十一个参数为 ${11} !"
echo "参数总数有 $# 个!"
echo "作为一个字符串输出所有参数 $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
Shell 重定向
输出重定向
复制代码
1
2
3
4
# 将内容写进文件 file1 中,覆盖写入
command1 > file1
# 将内容写进文件 file1 中,追加写入
command1 >> file1
输入重定向
复制代码
1
2
# 将文件 file1 中的内容作为输入
command1 < file1
重定向命令表
命令 | 说明 |
---|---|
command > file | 将输出重定向到 file |
command < file | 将输入重定向到 file |
command >> file | 将输出以追加的方式重定向到 file |
n > file | 将文件描述符为 n 的文件重定向到 file |
n >> file | 将文件描述符为 n 的文件以追加的方式重定向到 file |
n >& m | 将输出文件 m 和 n 合并 |
n <& m | 将输入文件 m 和 n 合并 |
<< tag | 将开始标记 tag 和结束标记 tag 之间的内容作为输入 |
一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:
- 标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据
标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据
标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息
Here Document
Here Document 是 Shell 一种特殊的重定向格式
基本格式
复制代码
1
2
3
command << delimiter
document
delimiter
表示将 delimiter 之间的内容 document 作为重定向输入内容
复制代码
1
2
3
4
5
6
# 计算行数
wc -l << EOF
hello
pinsily
hello world
EOF
/dev/null 文件
当希望执行的命令不输出时,可以将它重定向到 /dev/null 文件中,相当于屏蔽掉了
文件包含
基本格式
复制代码
1
2
3
. filename
# 或
source filename
实例
test1.sh
复制代码
1
2
3
#!/bin/bash
myname="pinsily"
test2.sh
复制代码
1
2
3
4
5
6
7
#!/bin/bash
#使用 . 号来引用test1.sh 文件
. ./test1.sh
# 或者使用以下包含文件代码
# source ./test1.sh
echo "myname is ${myname}"
最后
以上就是正直戒指最近收集整理的关于【Shell】-- 入门笔记(2):流程控制,重定向及文件包含的全部内容,更多相关【Shell】--内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复