您的位置:首页 > 运维架构 > Shell

【Shell】-- 入门笔记(2):流程控制,重定向及文件包含

2017-05-14 15:42 477 查看

Shell 流程控制

if else

if

if condition
then
command1
command2
...
commandN
fi


if else

if condition
then
command1
command2
...
commandN
else
command
fi


if else-if else

if condition1
then
command1
elif condition2
then
command2
else
commandN
fi


for 循环

for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done


while 语句

while condition
do
command
done


可以连续读取键盘的信息

echo '按下 <CTRL-D> 退出'
echo -n '输入你最喜欢的电影名: '
while read FILM
do
echo "是的!$FILM 是一部好电影"
done


until 循环

until condition
do
command
done


case 语句

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 函数

简单函数

#!/bin/bash

helloFun(){
echo "hello world"
}
echo "-----函数开始执行-----"
helloFun
echo "-----函数执行完毕-----"


函数参数

#!/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 重定向

[b]输出重定向[/b]

# 将内容写进文件 file1 中,覆盖写入
command1 > file1

# 将内容写进文件 file1 中,追加写入
command1 >> file1


[b]输入重定向[/b]

# 将文件 file1 中的内容作为输入
command1 < file1


 [b]重定向命令表[/b]

命令说明
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流中写入错误信息

[b]Here Document[/b]

Here Document 是 Shell 一种特殊的重定向格式

基本格式

co
4000
mmand << delimiter
document
delimiter


表示将 delimiter 之间的内容 document 作为重定向输入内容

# 计算行数
wc -l << EOF
hello
pinsily
hello world
EOF


[b]/dev/null 文件[/b]

当希望执行的命令不输出时,可以将它重定向到 /dev/null 文件中,相当于屏蔽掉了

文件包含

[b]基本格式[/b]

. filename
# 或
source filename


[b]实例[/b]

test1.sh

#!/bin/bash

myname="pinsily"


test2.sh

#!/bin/bash

#使用 . 号来引用test1.sh 文件
. ./test1.sh

# 或者使用以下包含文件代码
# source ./test1.sh

echo "myname is ${myname}"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: