bash编程 :if,case语句
2015-09-19 17:02
525 查看
bash之条件判断(选择执行) 单分支if语句: if CONDITION; then if-true-分支 fi 示例:写一个脚本,如果文件不存在,就创建文件 #!/bin/bash # file=/root/fstab if [ ! -f $file ]; then touch $file fi 双分支if语句: if CONDITION; then if-true-分支 else if-true-分支 fi 示例:写一个脚本,如果文件不存在,就说文件不存在,并创建文件 #!/bin/bash # file=/root/fstab if [ -f $file ]; then echo "file is not exists.." else touch $file echo "touch file $file finished" fi 多分支if语句 if CONDITION1; then if- CONDITION1-true-分支 elif CONDITION2; then if- CONDITION2-true-分支 else 其他-分支 fi 示例:写一个脚本,传递一个参数,判断给定的参数类型 #!/bin/bash # if [ $# -lt 1 ]; then echo "Plz enter a file path." exit 1 fi if [ -f $1 ]; then echo "$1 is a file." elif [ -d $1 ]; then echo "$1 is a mulu" elif [ -b $1 ]; then echo "$1 is a kuai." else echo "unknow file type" fi case语句: 简洁版多分支if语句; 使用场景:判断某变量的值是否为多种情形中的一种时使用; 语法: case$VARIABLE in PATTERN1) 分支1 ;; PATTERN2) 分支2 ;; PATTERN3) 分支3 ;; ... *) 分支n ;; Esac 示例:判断用户给的参数,是数值,字符或者是其他类型 #!/bin/bash # read -p "Plz enter a shuzhi"char case $char in [a-z]) echo "A character" ;; [0-9]) echo "A digit" ;; *) echo "A unknown character" esac 示例:根据用户给定的选项,做相应的操作 #!/bin/bash # prog=$(basename $0) localfile="/var/tmp/$prog" #echo $localfile if [ $# -lt 1 ]; then echo "Usage: $prog start|stop|restart|status" exit 1 fi case $1 in start) if [ -f $localfile ]; then echo "$prog is starting yet" else touch $localfile && echo "starting $prog ok" || echo "starting $prog failed.." fi ;; stop) if [ -f $localfile ]; then rm -rf $localfile && echo "$prog is stoped..." else echo "$prog stopeding.." fi ;; restart) if [ -f $localfile ]; then rm -rf $localfile && touch $localfile && echo "restarting $prog ok..." else touch $localfile && echo "$prog is stoped,starting $prog ok..." fi ;; status) if [ -f $localfile ]; then echo "$prog is running..." else echo "$prog is stoping..." fi ;; *) echo "Usage: $prog start|stop|restart|status" exit esac
相关文章推荐
- Python Shell 值的传送
- Linux shell的条件判断、循环语句及实例
- Linux shell的条件判断、循环语句及实例
- bash编程 :循环语句
- shell脚本基础进阶(二)----变量及运算符
- Linux Shell
- 通过XShell链接virtualbox中的CentOS
- shell sed实例详解
- shell重定向的细节分析
- windows通过使用xShell远程linux上传文件
- 利用shell脚本“综合、集中”查看linux server常用软硬件信息 推荐
- CentsOS 6.3 — 安装bash-completion
- xshell linux与Windows传输文件 sz rz
- Bash shell 快捷键
- linux shell — 2.Linux的档案属性和目录配置
- Linux系统Shell简述
- 一个简单的自动创建Shell脚本的脚本
- Shell 学习笔记
- 如何在shell中判断一个文件是否为空
- File permissions: why can't I list a directory?