Linux基礎--shell指令碼(4)
判斷語句
格式五
if [ con1 ]
then
cmd1
elif [ con2 ]
then
cmd2
elif [ con3 ]
then
cmd3
.....
else
cmd_failed
fi
bc : 超文字計算器
退出:quit
==================================
格式六:
case $var in
value1)
cmd1
;;
value2)
cmd2
;;
value3)
cmd3
;;
....
*)
cmd_failed
;;
esac
=========================================
迴圈語句:
for while until
for格式一
for varname in value1 value2 ... valuen
do
cmd
done
for varname in $(seq stat_value step end_value)
do
cmd
done
`` : 反引號
“” :雙引號
'' : 單引號
案例1:
[[email protected] test]# touch a b 無雙引號或者單引號
[[email protected] test]# ll
總計 0
-rw-r--r-- 1 root root 0 06-28 20:22 a
-rw-r--r-- 1 root root 0 06-28 20:22 b
[[email protected] test]# touch "aa bb" 雙引號
[[email protected] test]# ll
總計 0
-rw-r--r-- 1 root root 0 06-28 20:22 a
-rw-r--r-- 1 root root 0 06-28 20:22 aa bb
-rw-r--r-- 1 root root 0 06-28 20:22 b
[[email protected] test]# touch 'aaa bbb' 單引號
[[email protected] test]# ll
總計 0
-rw-r--r-- 1 root root 0 06-28 20:22 a
-rw-r--r-- 1 root root 0 06-28 20:22 aaa bbb
-rw-r--r-- 1 root root 0 06-28 20:22 aa bb
-rw-r--r-- 1 root root 0 06-28 20:22 b
表示"" 和 '' 都會遮蔽空格
案例2:
[[email protected] test]# echo $USER
root
[[email protected] test]# mkdir $USER
[[email protected] test]# ll
總計 4
drwxr-xr-x 2 root root 4096 06-28 20:26 root
[[email protected] test]# mkdir "$USER"
[[email protected] test]# ll
總計 4
drwxr-xr-x 2 root root 4096 06-28 20:27 root
[[email protected] test]# mkdir '$USER'
[[email protected] test]# ll
總計 4
drwxr-xr-x 2 root root 4096 06-28 20:27 $USER
雙引號不會遮蔽特殊字元,單引號可以遮蔽特殊字元
date : 表示顯示時間命令
年 :%Y
月 :%m
日 :%d
小時 :%H
分鐘 :%M
秒 :%S
星期 :%w
案例:
[[email protected] sh]# date +%Y
2018
[[email protected] sh]# date +%y
18
cal :
顯示日曆
案例
cal : 表示顯示當前年當前月資訊
cal year : 表示顯示當指定年的12個月資訊
cal month year : 表示顯示當前年指定月的資訊
案例:
[[email protected] test]# date
2018年 06月 28日 星期四 20:31:10 CST
[[email protected] test]# date 表示執行命令
2018年 06月 28日 星期四 20:31:10 CST
[[email protected] test]# mkdir date 建立目錄
[[email protected] test]# ll
總計 4
drwxr-xr-x 2 root root 4096 06-28 20:32 date 就是命令名
[[email protected] test]# rm * -rf
[[email protected] test]# mkdir `date` 建立目錄
[[email protected] test]# ll
總計 24
drwxr-xr-x 2 root root 4096 06-28 20:32 06月
drwxr-xr-x 2 root root 4096 06-28 20:32 2018年
drwxr-xr-x 2 root root 4096 06-28 20:32 20:32:52
drwxr-xr-x 2 root root 4096 06-28 20:32 28日
drwxr-xr-x 2 root root 4096 06-28 20:32 CST
drwxr-xr-x 2 root root 4096 06-28 20:32 星期四
優先執行反引號的命令
for格式二
for ((init; con; add))
do
cmd;
done
一個迴圈是由四部分組成:
1 初始化部分
2 條件部分
3 增量部分
4 迴圈體
#!/bin/bash
for ((i = 1 初始化; i < 10 條件; i++ 增量))
do
echo -n "$i " 迴圈
done
echo
1 2 3 4 5 6 7 8 9
1 -> 2 -> 4 -> 3 => 2 -> 4 -> 3 => .... 條件不滿足,則退出
練習:
實現1 + 2 + 3 + ... + 100 = ?
for格式三:巢狀
for (())
do
for (())
do
....
done
.....
done
*
* *
* * *
* * *
* * * *
* * * * *
......
* * * * * * * * *
homework:
左上角
*
* *
* * *
* * * *
* * * * *
右上角
*
* *
* * *
* * * *
* * * * *
左下角
* * * * *
* * * *
* * *
* *
*
右下角
* * * * *
* * * *
* * *
* *
*
2 實現一個空三角形
*
* *
* *
* *
* *
* *
* * * * * * *