一、shell的基本格式、變量shell
# shell腳本中要加上解釋器 #! /bin/bash
bash
# 用腳本打印出hello worldless
#! /bin/bash
ide
echo "hello world"spa
exit命令行
參數:參數是一個存儲實數值的實體,腳本中通常被引用blog
#利用變量回顯hello world,下面例子會回顯兩個hello world。ip
#! /bin/bash字符串
a="hello world"get
echo $a
echo "hello world"
exit
若是參數後面加着其它內容,須要用{}
#! /bin/bash
a="hello world"
echo ${a},i am coming
exit
回顯結果:
#計算字符串長度,hello world 連空格,總共11
二、腳本退出
#一個執行成功的腳本返回值爲0,不成功爲非0
[root@localhost script]# clear
[root@localhost script]# sh hello.sh
hello world,i am coming
11
[root@localhost script]# echo $?
0
#判斷一個目錄內是否有某個文件,有則回顯file exsit ,沒有則返回1
[root@localhost script]# cat test.sh
#! /bin/bash
cd /home
if [ -f file ];then
echo "file exsit"
else
exit 2
fi
[root@localhost script]# sh test.sh
[root@localhost script]# echo $?
2
[root@localhost script]#
三、Test語句、if語句
test -d xx 目錄是否存在
test -f xx 文件是否存在
test -b xx 是否爲塊文件
test -x xx 是否爲可執行文件
A -eq B 判斷是否相等
A -ne B 判斷不相等
A -le B 小於等於
A -lt B 小於
A -gt B 大於
#if條件判斷語句
if [];then
......
else
......
fi
#if語句嵌套
if [];then
.......
elif [];then
.......
elif [];then
.......
else
......
fi
#test舉例,判斷test文件是否存在,若是存在對其進行備份操做。若是不在回顯信息
#例子:輸入一個數值判斷其在哪一個區間。小於80,大於100,位於80到100之間,用的是if嵌套!
[root@localhost script]# cat if.sh
#! /bin/bash
read -p "plz input a $num:" num
if [ $num -le 80 ];then
echo "num is less 80"
elif [ $num -ge 80 ] && [ $num -le 100 ];then
echo "num between 80 and 100"
else
echo "num is greater than 100"
fi
四、循環語句 for、while
for var in $var1 $var2 $var3 var4... $var
do
......
......
done
#例子:打印1到10數字
[root@localhost home]# cat for1.sh
#! /bin/bash
for var in {1..10}
do
echo "$var"
sleep 2
done
[root@localhost home]# sh for1.sh
1
2
3
4
5
6
7
8
9
10
[root@localhost home]#
#打印方塊內容 for嵌套
[root@localhost home]# sh for2.sh
*********
*********
*********
*********
*********
*********
*********
*********
*********
[root@localhost home]# cat for2.sh
#! /bin/bash
for ((i=1;i<10;i++))
do
for ((j=1;j<10;j++))
do
echo -n "*"
done
echo ""
done
# while循環,主要也是用於循環,另外還有continue(跳出continue下面語句,迴歸頂部命令行)、break(中止、退出循環)
#while語句
while [條件判斷]
do
......
......
done
#例子:根據條件判斷的,輸出1-10
[root@localhost script]# cat while.sh
#! /bin/bash
var=1
while [ $var -le 10 ]
do
echo $var
var=$[$var+1]
done
[root@localhost script]# sh while.sh
1
2
3
4
5
6
7
8
9
10
[root@localhost script]# echo $?
0