一、case分支语句
语法格式:
case $变量名 in
模式1)
命令序列1
;;
模式2)
命令序列2
;;
*)
默认执行的命令序列
;;
esac
case代码实例
#!/bin/bash read -p "press some key ,then press return :" KEY case $KEY in [a-z]|[A-Z]) echo "It's a letter." ;; [0-9]) echo "It's a digit." ;; *) echo "It's function keys、Spacebar or other ksys." ;; esac
其中read -p 是从控制台读取字符串
二、if分支
语法格式
if command
then
commands
fi
或者
if command:then
commands
fi
或者
if command
then
commands
else
commands
fi
或者
if command1
then
commands
elif command2
then
commands
fi
test命令语法
if test condition then commands fi 或者 if [condition] then commands fi
test数值的比较
n1 -eq n2 检查n1是否与n2相等
n1 -ge n2 检查n1是否大于等于n2
n1 -gt n2 检查n1是否大于n2
n1 -le n2 。。。。。
n1 -lt n2 。。。。。
n1 -ne n2 。。。。。。
test字符串比较
str1 = str2
str1 != str2
str1 < str2
str1 > str2
-n str1 检查str1的长度是否非0
-z str1 检查str1的长度是否为0
注意,使用的时候<或者 >需要转义\
代码实例
#!/bin/bash var1=10 var2=11 if [ $var1 -gt 5 ] then echo "The test value $var1 is greater than 5" fi if [ $var1 -eq $var2 ] then echo "The values are equal" else echo "The valus are fifferent" fi 运行结果: The test value 10 is greater than 5 The valus are fifferent 需要注意的是[]左右内侧必须有空格,否则运行报错
三、文件比较
| 比较 | 描述 |
| -d file | 检查file是否存在并是一个目录 |
| -e file | 检查file是否存在 |
| -f file | 检查file是否存在并是一个文件 |
| -r file | 检查file是否存在并可读 |
| -s file | 检查file是否存在并非空 |
| -w file | 检查file是否存在并可写 |
| -x file | 检查file是否存在并可执行 |
| -O file | 检查file是否存在并属于当前用户所有 |
| -G file | 检查file是否存在并且默认组与当前用户相同 |
| file1 -nt file2 | 检查file1是否比file2新 |
| file1 -ot file2 | 检查file1是否比file2旧 |
代码实例
#!/bin/bash if [ -e $HOME ] then echo "home exist" else echo "home not exist" fi
四、for语法
for var in list do commands done
实例
#!/bin/bash for var in Alaska Ae we wer do echo the next state is $var done 运行结果: $ sh fortest.sh the next state is Alaska the next state is Ae the next state is we the next state is wer
解析文本文件,并循环输出文件内容
#!/bin/bash
IFS.OLD=$IFS
IFS=$'\n'
for entry in `cat /etc/passwd`
do
echo "values in $entry"
IFS=:
for value in $entry
do
echo " $value"
done
done
IFS=$IFS.OLD
while,until,..
本文详细介绍了Shell脚本中的几种关键控制结构,包括case语句、if分支、文件比较及循环结构for和while等。通过具体的代码示例,帮助读者理解如何在脚本中实现条件判断和循环操作。
33万+

被折叠的 条评论
为什么被折叠?



