if ((10>5));then #两个括号用在if中表示判断大小,后面接分号,then echo 10 is greater than 5 elif ((10==5));then echo 10 equals 5 else echo 5 is greater than 10 fi #以反if结尾表示结束
例子:判断目录是否存在,不存在就创建
1 2 3 4 5 6 7 8 9 10
#!/bin/bash #make directory if it's not exist #author narcissus
if [ ! -d ./test2 ];then echo create direcotry test2 mkdir test2 else echo directory exists fi
cd ~ #进入家目录 if [ $UID -eq 0 ];then #判断如果是root用户 for i in `ls /home/` #列出所有普通用户 do cd /home/$i #进入普通用户目录 for j in `ls` #循环用户下的文件/目录 do echo $j #打印 done done else #如果是普通用户 for j in `ls` #循环用户下的文件/目录 do echo $j #打印 done fi
while循环
1 2 3 4
while 条件 do action done
简单的循环
1 2 3 4 5 6 7
#!/bin/bash i=0 while [[ $i -lt 10 ]] do echo "the number is $i" ((i++)) done
从终端读取数字并计算数字阶乘
1 2 3 4 5 6 7 8 9 10 11
#!/bin/bash
read m i=1 y=1 while [[ $i -lt $m ]] do ((i++)) ((y=$y*$i)) done echo "!m= $y"
实现从指定文件夹读取数据并显示
1 2 3 4 5 6
#!/bin/bash
while read i do echo $i done < ~/.zshrc
until循环
1 2 3 4
until 条件 do action done
与while差不多
case选择
1 2 3 4 5 6 7 8
case $arg in pattern1) action;; pattern2) action;; *) action;; esac
*) 代表不在选择范围内的数据,即其它
选择安装lamp
1 2 3 4 5 6 7 8 9 10 11 12
#!/bin/bash
case $1 in apache) echo "install apache";; mysql) echo "install mysql";; php) echo "install php";; *) echo "please choose the right package";; esac
$1 用于读取终端输入的第一个参数
select选择
select用于从终端读取选择的数据,与case搭配起来使用
1 2 3 4
select var in "arg1" "arg2" "arg3" .... do action done
PS3="please select the one you want to install: " select i in "apache" "mysql" "php" do case $i in apache) echo "install apache" ;; mysql) echo "install mysql" ;; php) echo "install php" ;; *) echo "your choise is wrong" ;; esac done