2010年9月13日 星期一

Shell script 練習(if then...else...)

<1>testroot.sh
#判斷執行程式的帳號是否為root
#!/bin/bash

w=$(whoami)
[ "$w" != "root" ] && echo "$w have no permission,need root " && exit 1
[ "$w" == "root" ] && echo "you are root"
exit 0


<2>param01.sh
#判斷option是否為"-a"
#!/bin/bash


if [ "$#" != "1" ] || [ "$1" != "-a" ]; then
        echo "error option"
        exit 1
fi

echo "-a ok"
exit 0

<3>mytar.sh
#判斷接續的檔案副檔名是否為.tar
#!/bin/bash

if [ "${1##*.}" == "tar" ]; then        
#${1}=$1,{}是為了執行##*.表示由左向右抓出最後一個.右邊的所有文字,單一個#表示由左向右第一個.右邊的所有文字
        echo "This appears to be a tarball."
else
        echo "At firs glance,this does not appear to be a tarball"
fi
exit 0

<4>touchsh
#判斷檔案是否附檔名為.sh如是給予執行權限
#!/bin/bash

[ ! -f "$1" ] && echo "file no exist!" && exit 1
if [ "$#" != "1" ] || [ "${1##*.}" != "sh" ]; then
        echo "error option"
        exit 1
fi
chmod +x $1
exit 0

沒有留言:

張貼留言