Shell 中的 if 流程判断语句:


 

        此链接通往 Bash Shell 编程学习的目录导航 ,从入门到放弃,感兴趣的可以去看看:


1、if 语句的格式:

if 语句很简单,就是满足条件,则执行... 反正则执行...

"单条件:"

if [ 条件表达式 ];then
    语句1...
fi

——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

"双条件:"

if [ 条件表达式 ];then
    语句1...
else 
    语句2...
fi

——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

"多条件:"

if [ 条件表达式 1 ];then
   语句1...
elif [ 条件表达式2 ];then
   语句2...
elif [ 条件表达式3 ];then
   语句3...
else
   语句4...
fi

2、综合实例:

判断文件是什么类型:

root@zhengzelin:~# vim test.sh 
read -e -p "请输入您要查看的文件或目录(请写绝对路径,可以使用tab补齐功能):" test
file=$(ls -alF $test | awk '{print $1}' | grep -o -)    
if [[ -d $test ]];then
   echo -e "\e[1;34mthis is a dir..\e[0m"
   sleep 1
   echo "查询完成,正在退出...";exit
elif [[ "$file" == "-" ]];then
   echo -e "\e[1;33m这是一个普通文件..\e[0m"
   sleep 1
   echo "查询完成,正在退出...";exit
elif [[ -L $test ]];then
   yuan=$(ls -alF $test | awk '{print $NF}')
   echo  -e "\e[1;32m这是一个连接文件:源文件为:$yuan\e[0m"
   sleep 1
   echo "exit...";exit
elif [[ -c $test || -b $test ]];then
   echo -e "\e[1;35m这是一个特殊文件(块设备文件或字符设备文件)\e[0m"
   sleep 1
   exit;
else 
   echo "此文件不存在..."
fi

总结:因为 -f 和 -L 这里,当你是一个链接文件的时候,-f 的返回值也是 0,所以这里有点麻烦!所以我只能截取 “-” 了! - 代表普通文件。

root@zhengzelin:~# ./test.sh 
请输入您要查看的文件或目录(请写绝对路径,可以使用tab补齐功能):/r
root/ run/  
请输入您要查看的文件或目录(请写绝对路径,可以使用tab补齐功能):/root/
this is a dir..
查询完成,正在退出...
发布了99 篇原创文章 · 获赞 72 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ljlfather/article/details/105205798