Linux shell case条件判断及位置变量
2024-08-31 08:35:40
case语句使用于需要进行多重分支的应用情况
case分支判断结构
语法:
case 变量名称 in
value1)
statement
statement
;;
value2)
statement
statement
;;
*)
statement
statement
;;
esac
case语句结构特点如下:
case行尾必须为单词 in 每个模式必须以右括号 ) 结束
双分号 ;; 表示命令序列结束
case语句结构特点如下:
匹配模式中可是使用方括号表示一个连续的范围,如[0-9];使用竖杠符号“|”表示或。
最后的“*)”表示默认模式,当使用前面的各种模式均无法匹配该变量时,将执行“*)”后的命令序列。
编写脚本,判断用户输入的字符串
#!/bin/bash
#
read -p "输入字符串:" str
case $str in
linux|Linux)
echo "windows"
;;
windows|Windows)
echo "linux"
;;
*)
echo "other"
;;
esac
运行效果:
[root@wei case]# bash 1.sh
输入字符串:linux
windows
特殊变量:
位置变量
$1,$2,$3...........$9,$1{10}
$1:命令的第1个参数
$0 命令本身
$# 命令参数的个数
使用位置变量
#!/bin/bash
#
case $1 in
linux|Linux)
echo "windows"
;;
windows|Windows)
echo "linux"
;;
*)
echo "other"
esac
执行效果
[root@wei case]# ./2.sh linux
windows
判断字符是为空
#!/bin/bash
#
if [ -z $1 ];then #判断字符串是否为空
echo "使用:./2.sh{linux/windows}"
exit 9
fi
case $1 in
linux|Linux)
echo "windows"
;;
windows|Windows)
echo "linux"
;;
*)
echo "other"
esac
执行效果
[root@wei case]# ./2.sh
使用:./2.sh{linux/windows}
$0 命令本身
$# 命令参数的个数
示例:
#!/bin/bash
#
if [ $# -ne 1 ];then
echo "使用:$0{linux/windows}"
exit 9
fi
case $1 in
linux|Linux)
echo "windows"
;;
windows|Windows)
echo "linux"
;;
*)
echo "other"
esac
执行效果:
[root@wei case]# /shell/case/2.sh
使用:/shell/case/2.sh{linux/windows}
[root@wei case]# ./2.sh
使用:./2.sh{linux/windows}
去除文件所在的路径名:
basename [路径文件]
[root@wei case]# basename /etc/fstab
fstab
获取文件所在的路径名:
dirname [路径文件]
[root@wei case]# dirname /etc/fstab
/etc
脚本
#!/bin/bash
#
if [ $# -ne 1 ];then
echo "使用:$(basename $0){linux/windows}"
exit 9
fi
case $1 in
linux|Linux)
echo "windows"
;;
windows|Windows)
echo "linux"
;;
*)
echo "other"
esac
执行效果
[root@wei case]# /shell/case/2.sh
使用:2.sh{linux/windows}
最新文章
- Log4net入门(控制台篇)
- Hibernate的三种状态及对象生命周期
- Linux下几种文件传输命令 sz rz sftp scp
- mvc正则@符号js报错解决办法
- androidd 程序默认安装位置和数据存储位置(公用和私用)
- asp.net mvc 动态显示不同的部分视图
- QA笑话----杂思
- 2301: [HAOI2011]Problem b
- Android APN配置
- 深入浅出—JAVA(4)
- 如何查找Linux的函数定义的位置?
- Web调用安卓,苹果手机摄像头,本地图片和文件
- 【XSY2727】Remove Dilworth定理 堆 树状数组 DP
- Elastic Job入门(1) - 简介
- img格式镜像转ISO格式
- 迷你音乐播放器v1.0正式上线!
- make INSTALL_MOD_PATH=path_dir modules_install
- 51ll网产品信息保存为txt文件
- Android Service总结03 之被启动的服务 -- Started Service
- jquery.lazyload插件实现图片延迟加载
热门文章
- 手机日期控件mobiscroll
- 【Excel】截取字符 LEFT(A1,2) RIGHT(A1,2) MID(SHEET1!E2,1,9)
- 三层交换机RIP动态路由实验
- <;Random>; 384 398
- [LeetCode] 145. Binary Tree Postorder Traversal 二叉树的后序遍历
- 单调队列优化DP(超详细!!!)
- 打造个人专属网盘nextcloud
- SpringCloud项目中使用Nacos作为注册中心
- lombok的使用以及其中的坑
- CF 715 E. Complete the Permutations