※Shell Script
- 寫一個shell script
cd ~/bin
vi sh1
#!/bin/bash 指定執行script 時的shell,若不指定時則會以系統內定的shell 執行 (echo $SHELL)
clear
date
cal
- 設定為可執行並且執行
chmod a+x sh1
- 寫一個可以輸入的程式
vi ~/bin/sh2
#!/bin/bash
echo “Input your name:”
read name
echo “welcome : ~ $name”
- 設定為可執行並執行
chmod a+x sh2
./sh2
※常用運算子
字串運算子
- = = 是否相等
- != 是否不相等
數值運算子
- -eq 是否相等
- -ne 是否不相等
- -gt 是否大於
- -ge 是否大於等於
- -lt 是否小於
- -le 是否小於等於
檔案運算子
- -e 是否存在
- -f 是否為檔案
- -d 是否為目錄
- -r 是否為可讀取
- -w 是否為可寫入
- -x 是否為可執行
test 運算式
test 100 = = 100 判斷100是否等於100
echo $? 回應判斷的結果 0 為真 1 為假
- 寫一個程式判斷目錄是否存在
vi ~/bin/sh3
echo “Input Directory:” 晝面顯示提示文子輸入
read dir 讀取輸入,並將輸入的值放到dir 變數中
tset -d $dir && echo “Directory exists”
使用tset 運算式運算目錄是否存在,若為真並顯示訊息
tset -d $dir || echo “Directory not exists” 使用tset 運算式運算目錄是否存在,若為真並顯示訊息 - 給預權限並執行
chmod a+x sh3
- 使用if 判斷式判斷目錄是否存在
vi ~/bin/sh4
#!/bin/bash
echo “Input Directory”
read dir
if test -d $dir
then
echo “Directory exists”
else
echo “Directory not exist”
fi
- 寫一壓縮程式並根據輸入的帳號備份不同的目錄
#!/bin/bash
echo “Input account:”
read acct
cd /home
if test -n “$acct” –a -d “$acct” 判斷輸入的非空白並且為是目錄
then
tar -zcvf /tmp/$acct.tar.gz $acct/ 備份檔名為輸入的帳號及home 下的帳號資料
else
echo “account ””$acct” not exists
fi
- 製作一備份程式以日期為檔名
echo input user path:
read path
if test -n "$path" -a -d "$path"
then
DIR=`dirname $path`
BASE=`basename $path`
cd $DIR
DATE=`date +%Y%m%d`
tar -zcvf /tmp/$BASE-$DATE.tar.gz $BASE/
else
echo $path not exists.
fi
- 製作會自動加入流水號檔名的備份
- 顯示檔名後可以自動修改副檔名為doc
- for 迴圈範例
- 使用While 迴圈檢查系統網路是否正常
echo input user path:
read path
if test -n "$path" -a -d "$path"
then
DIR=`dirname $path`
BASE=`basename $path`
cd $DIR
for ((n=1; n<1000; n++))
do
if test ! -f /tmp/$BASE-$n.tar.gz
then
break
fi
done
tar -zcvf /tmp/$BASE-$n.tar.gz $BASE/
else
echo $path not exists.
fi
cd dir2
for f in file*
do
file=`echo $f | cut -d. -f1`
echo $file
mv $f $file.doc
done
for ((i=1; i<100; i++))
do
touch dir2/file$i.txt
done
while true
do
if ping -c1 -w2 168.95.1.1 > /dev/null 2>&1
then
echo network ok
sleep 3
else
echo network fail
echo network fail | mail -s "error" root
sleep 1
fi
done
留言列表