Shell语法 【if while for】

【if语法 测试条件 判断语句】 转自:http://lovelace.blog.51cto.com/1028430/1211353 【while for循环】 转自:https://blog.csdn.net/weixin_36586564/article/details/78681117 for 变量 in 列表 do command1 command2 ... commandN done 也可写成: for var in list; do 读取列表中的值 for test in Alabama BOb Tom Console do echo The next state is $test done 读取列表中的复杂值 有两种解决办法: *使用转义字符(反斜线)来将单引号转移; *使用双引号来定义用到单引号的值 for test in I don\'t think if "this'll" work do echo The next state is $test done The next state is I The next state is don't The next state is think The next state is if The next state is this'll The next state is work 从命令读取值 有两种方式可以将命令输出赋值给变量: (1)反引号字符(`) (2)$()格式 例如: test=`date` test=$(date) #!/bin/bash # reading values from a file file="states" for state in $(cat $file) do echo "visit beautiful $state" done states文件内容: Alabama BOb Tom Console 执行结果: visit beautiful Alabama visit beautiful BOb visit beautiful Tom visit beautiful Console 字段分割符 造成这个问题的原因是特殊的环境变量IFS,叫作内部字段分隔符。默认情况下,bash shell会将下列字符当作字段分隔符: *空格 *制表符 *换行符 可参考的安全实践是在改变IFS之前保存原来的IFS值,之后再恢复它 IFS.OLD=$IFS IFS=$'\n' <在代码中使用新的IFS值> IFS=$IFS.OLD 使用通配符读取文件目录 for file in /proc/*; do echo $file is file path \! ; done 类C风格for循环的语法格式 for((expr1; expr2; expr3)) do command command ... done #!/bin/bash #使用类C风格for循环输出1~5 for ((integer = 1; integer <= 5; integer++)) do echo "$integer" done 利用while循环计算1到100的和: let 命令是 BASH中用于计算的工具,用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量。如果表达式中包含了空格或其他特殊字符,则必须引起来 注意:bash的工具,如果用 sh cmd.sh 执行脚本,let命令不识别 i=1 sum=0 while [ $i -le 100 ] do let sum=sum+$i let i++ done 使用read结合while循环读取文本文件 #从file文件中读取文件内容赋值给line while read -r line #(使用参数r会屏蔽文本中的特殊符号,只做输出不做转译) do echo $line #输出文件内容 done < $file
posted @ 2018-09-06 00:09  A.ArmStrong  阅读(220)  评论(0编辑  收藏  举报