结构化命令
if else
if condition
then
statements(s)
fi
-
condition是判断条件- 如果condtion成立返回true、将执行then中的语句
- 如果condtion不成立、返回false、那么不会执行任何语句
注意:最会必须要用fi来闭合
#!/bin/bash
read a
read b
if (($a == $b))
then
echo "a与b相等"
else
echo "a与b不相等"
fi
可以交互起来、哈哈哈
echo "请输入你的名称"
read name
echo "请输入密码"
read password
echo $name"-"$password
if elif else
if condition1
then
statement1
elif condition2
then
statement2
elif condition3
then
statement3
else
statementn
fi
这个没有什么好说的和我们日常的语法没有区别、只需要注意if 和elif后面都需要then
嵌套if语句
if条件测试中可以再嵌套if条件测试
if [条件1成立]
then
if [条件2成立]
then
code...
fi
case in
语法和switch case不一致、功能逻辑是一样的 基本格式
case expression in
pattern1) statement1;;
pattern2) statement2;;
pattern3) statement3;;
*) default statement
esac
for
for 命令用于创建遍历系列值的循环。每次迭代都是用其中一个值来执行已定义好的一组命令。
基本格式
for var in list
do
commands
done
#!/bin/bash
# basic for command
for item in Guangdong Sichuan Henan Heilongjiang Zhejiang Jiangsu
do
echo The next province is $item
done
-
for循环假定每一个值都是使用空格分割的
-
当列表的值有特殊的字符、可以使用转移字符解决
-
当某个值的两边使用双引号、shell并不会将双引号当作值的一部分
从命令中读取值
生成列表中所需值的另外一个途径就是使用命令的输出。可以用命令替换来执行任何能产生输出的命令,然后在 for 命令中使用该命令的输出。
# !/bin/bash
# reading values from a txt
file="provinces.txt"
echo $file
for province in $(cat $file)
do
echo "Visit beautiful $province"
done
同目录下文件province.txt
Guangdong
Sichuan
Henan
Heilongjiang
Zhejiang
Jiangsu
该例子在命令替换中使用了 cat 命令来输出文件 provinces 的内容。for 命令仍然以每次一行的方式遍历了 cat 命令的输出,假定每个值都是在单独的一行上。但这并没有解决数据中有空格的问题。如果你列出了一个名字中有空格的值,for 命令仍然会将每个单词当作单独的值。 上述示例文件执行路径为相同目录,如果是其他目录下,需要使用全路径名来引用文件位置。
更改字段分隔符
造成上述无法分隔含有空格的值原因是特殊的环境变量 IFS,叫作 内部字段分隔符(internal field separator)。IFS 环境变量定义了 Bash Shell 用作字段分隔符的一系列字符。默认情况下,Bash Shell 会将下列字符当作字符分隔符:
- 空格
- 制表符
- 换行符
如果 Bash Shell 在数据中看到了这些字符中的任意一个,它就会假定这表明了列表中一个新数据字段的开始。在处理可能含有空格的数据(比如文件名)时,这会非常麻烦,就像你上一个脚本示例中看到的。
在 Shell 脚本中临时更改 IFS 环境变量,可以限制被 Bash Shell 当作字段分隔符的字符。
#/bin/bash
# reading values from a file
file="province.txt"
IFS=$'\n'
for province in $(cat $file)
do
echo "Visit beautiful $province"
done
用通配符读取目录
要用 for 命令来自动遍历目录中的文件,必须在文件名或路径名中使用通配符。文件扩展匹配是生成匹配指定通配符的文件名或路径名的过程。
如果不知道所有文件名,这个特性在处理目录中的文件时就非常有用。
#!/bin/bash
# iterate through all the files in a directory
for file in ./*
do
if [ -d "$file"]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi
done
c语言风格的for命令
基本格式
for (( variable assignment ; condition ; iteration process ))
for (( i=1; i<= 10; i++ ))
do
echo "The next number is $i"
done
while
基本格式
while test command
do
other commands
done
常见的用法是方括号来检查循环命令中用到的 Shell 变量的值:
#/bin/bash
# while command test
var1=10
while [ $var1 -gt 0 ]
do
echo $var1
var1=$[ $var1 - 1 ]
done
until
util 命令和 while 命令工作的方式完全相反。util 命令要求你指定一个通常返回非零退出状态码的测试命令。只要测试命令的退出状态码不为 0,Bash Shell 才会执行循环中列出的命令。一旦测试命令返回了退出状态码 0,循环就结束了。
基本格式:
util test commands
do
other commands
done
eg:
#!/bin/bash
# using the until command
num=100
until [ $num -eq 0 ]
do
echo $num
num=$[ $num - 25 ]
done