shell脚本语法
来源:互联网 发布:退火算法 matlab 编辑:程序博客网 时间:2024/06/06 17:33
条件测试:test [
-测试一个条件是否成立,
- 如果结果为真,则结果=0
- 如果结果为假,则结果=1
python@ubuntu:~/1004$ var=2python@ubuntu:~/1004$ test $var python@ubuntu:~/1004$ echo $?0python@ubuntu:~/1004$ test $var -gt 5python@ubuntu:~/1004$ echo $?1
或者:
(注意: 两边加空格)
python@ubuntu:~/1004$ [ $var -gt 1 ]python@ubuntu:~/1004$ echo $?0
语法错误:
python@ubuntu:~/1004$ [ $s1 = $s4 ]bash: [: hello: 需要一元表达式需要加"" : [ "$s1" = "$s4" ]
if/then/elif/else/fi
实现分支控制
- 判断是否事目录-d (-f文件)
- fi:判断if结束的关闭标签
#! /bin/shif [ -d ~/Desktop ]; then echo "Desktop is dir" echo "dimples"fi
source t2.sh
- :空命令(不做任何事,执行总是真)
- read命令:等待用户输入一行字符串,存到shell变量中
#! /bin/shecho "it is morniing? yes or no"read YES_OR_NOif [ "$YES_OR_NO" = "yes" ]; then echo "早上好"elif [ "$YES_OR_NO" = "no" ]; then echo "中午好"else echo "sorry" exit 1fiexit 0
python@ubuntu:~/1004$ vi t3.shpython@ubuntu:~/1004$ chmod a+x t3.shpython@ubuntu:~/1004$ ./t3.shit is morniing? yes or noyes早上好
case/esac
- 类似C语言的switch/case语句
- esac表示case语句块的结束
#! /bin/shecho "is it morning"read YES_OR_NOcase "$YES_OR_NO" inyes|y|Yes|YES) echo "早上好";;[nN]*) echo "中午好";;*) echo "sorry" exit 1;;esacexit 0
- source执行结果会传递给shell,shell退出了
- 必须用chmod:
python@ubuntu:~/1004$ chmod a+x t4.shpython@ubuntu:~/1004$ ./t4.sh
case语句的例子可以在系统服务的脚本目录 /etc/init.d中找到。这个目录下都是启动脚本程序。
循环语句
for/do/done
- 类似于foreach循环
- 反引号:``执行命令
#! /bin/shfor FRUIT in apple pear banana; do echo "I like $FRUIT" done
python@ubuntu:~/1004$ source t5.shI like appleI like pearI like banana
while/do/done
#! /bin/shecho "输入密码:"read PWDwhile [ "$PWD" != "111111" ]; do echo "Sorry, try again" read PWDdone
python@ubuntu:~/1004$ source t6.sh输入密码:1Sorry, try again2Sorry, try again111111
通过算数运算控制循环的次数:
- 用户最多可已输入5次密码,输入正确直接结束
#! /bin/shecho "请输入密码"read PWDCOUNTER=1while [ "$COUNTER" -lt 6 ]; do if [ "$PWD" != "123" ]; then #break if [ "$COUNTER" -eq 5 ]; then echo "输入错误,没有机会啦" else echo = "输入错误,再来一次" read PWD fi else echo "输入成功" break fi COUNTER=$(($COUNTER+1))done
阅读全文
0 0
- Shell脚本语法
- Shell脚本语法
- Shell脚本语法
- Shell脚本语法
- shell脚本语法
- windows Shell 脚本语法
- shell脚本语法
- Shell脚本语法-摘录
- Shell脚本语法
- shell脚本语法
- Shell脚本语法
- shell脚本基础语法
- Shell bash 脚本语法
- shell脚本语法
- shell 脚本基本语法
- Shell脚本语法
- Shell脚本语法
- Shell脚本语法
- gcc xx.c:(.text+0x11): undefined reference to `sqrt'
- Java(3-3)
- UVa 123|Searching Quickly|字符串处理
- 个人计划《2017-10-06》
- HYSBZ1941-Hide and Seek
- shell脚本语法
- 先码一个,try catch没有捕获到OutOFBoundsException
- DBSDFZOJ 模拟考试 命运 最小生成树+乱搞
- bat命令入门与高级技巧详解
- 160个练手CrackMe-004
- master -> master (non-fast-forward)和git ! [rejected] master -> master (fetch first)
- 前端之路——第七篇:整理目前疑问点/css必会伪类选择器/css媒体查询
- PAT 1025. 反转链表 (25)
- HDU