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

来源:互联网 发布:sql 2008 sa 密码 编辑:程序博客网 时间:2024/06/12 19:15

Shell 流程控制

if else

  • if
if conditionthen    command1     command2    ...    commandN fi
  • if else
if conditionthen    command1     command2    ...    commandNelse    commandfi
  • if else-if else
if condition1then    command1elif condition2 then     command2else    commandNfi

for 循环

for var in item1 item2 ... itemNdo    command1    command2    ...    commandNdone


while 语句

while conditiondo    commanddone

可以连续读取键盘的信息

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

until 循环

until conditiondo    commanddone

case 语句

echo '输入 1 到 4 之间的数字:'echo '你输入的数字为:'read aNumcase $aNum in    1)  echo '你选择了 1'    ;;    2)  echo '你选择了 2'    ;;    3)  echo '你选择了 3'    ;;    4)  echo '你选择了 4'    ;;    *)  echo '你没有输入 1 到 4 之间的数字'    ;;esac

Shell 函数

  • 简单函数
#!/bin/bashhelloFun(){    echo "hello world"}echo "-----函数开始执行-----"helloFunecho "-----函数执行完毕-----"
  • 函数参数
#!/bin/bashfunWithParam(){    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    documentdelimiter

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

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


/dev/null 文件

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


文件包含

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

test1.sh

#!/bin/bashmyname="pinsily"

test2.sh

#!/bin/bash#使用 . 号来引用test1.sh 文件. ./test1.sh# 或者使用以下包含文件代码# source ./test1.shecho "myname is ${myname}"
0 0
原创粉丝点击