天天看點

shell基礎知識

自棟校準時間 yum install -y ntp  使用ntpdate time.fudan.edu.cn去校準時間

date在腳本中最常用的幾個用法:

date +%F  xxxx-xx-xx

date +%T xx:xx:xx 

date +%Y 以四位數字格式列印年份

date +%y 以兩位數字格式列印年份

date +%m 月份

date +%d 日期

date +%H 小時

date +%M 分鐘

date +%S 秒

date +%s 時間戳

date +%w 星期,如果結果顯示0 則表示周日

有時在腳本中會用到一天前的日期:date -d "-2 days" +%F

定義變量的格式為 變量名=變量的值 當在腳本中引用變量時需要加上 ‘$’ 符号,這跟前面講的在shell中自定義變量是一緻的。

數學計算要用[ ]括起來并且外頭要帶一個 ‘$’

-lt (小于),-gt (大于),-le (小于等于),-ge (大于等于),-eq (等于),-ne (不等于)。

read -p "Please input a number: " x

read -p "Please input another number: " y

sum=$[$x+$y]

echo "The sum of the two numbers is: $sum"

read 指令就是用在這樣的地方,用于和使用者互動,把使用者輸入的字元串作為變量值。腳本執行過程如下:

有一個$0,不過它代表的是腳本本身的名字。

if  判斷語句; then

    command

fi

if  判斷語句  ; then

else

在if1.sh中出現了 ((a<60)) 這樣的形式,這是shell腳本中特有的格式,用一個小括号或者不用都會報錯,請記住這個格式

if  判斷語句一  ; then

elif  判斷語句二; then

-e :判斷檔案或目錄是否存在

-d :判斷是不是目錄,并是否存在

-f :判斷是否是普通檔案,并存在

-r :判斷文檔是否有讀權限

-w :判斷是否有寫權限

-x :判斷是否可執行

使用if判斷時,具體格式為:

if [ -e filename ] ; then

case  變量  in

value1)

          command

          ;;

value2)

value3)

*)

esac

上面的結構中,不限制value的個數, * 則代表除了上面的value外的其他值。

腳本中的 seq 1 5 表示從1到5的一個序列。

for 變量名 in 循環的條件; do

     command

done

while  條件; do

另外你可以把循環條件拿一個冒号替代,這樣可以做到死循環,阿銘常常這樣寫監控腳本:

while :; do

    sleep 3

在shell腳本中,函數一定要寫在最前面,

function 函數名() {

command