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


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 重定向

输出重定向
# 将内容写进文件 file1 中,覆盖写入
command1 > file1

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


输入重定向
# 将文件 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 一种特殊的重定向格式

基本格式

command << delimiter
    document
delimiter

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

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


/dev/null 文件

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


文件包含

基本格式
. filename
# 或
source filename
实例

test1.sh

#!/bin/bash

myname="pinsily"

test2.sh

#!/bin/bash

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

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

echo "myname is ${myname}"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值