我是靠谱客的博主 正直戒指,最近开发中收集的这篇文章主要介绍【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}"

最后

以上就是正直戒指为你收集整理的【Shell】-- 入门笔记(2):流程控制,重定向及文件包含的全部内容,希望文章能够帮你解决【Shell】-- 入门笔记(2):流程控制,重定向及文件包含所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(79)

评论列表共有 0 条评论

立即
投稿
返回
顶部