2011年6月27日

shell script 語法簡易範例

while迴圈

#!/bin/sh
read -r filename
while [ ! -f $filename ]; do
  echo "--> $filename does not exist"
  read -r filename
done
echo "$filename name OK"


until 迴圈

#!/bin/sh
until who | grep dino > /dev/null; do
  sleep 10
done
echo "dino has logged in"
 
for 迴圈

#!/bin/sh
for foo in *; do
  if [ -f $foo ]; then
     echo "$foo is a file"
  elif [ -d $foo ]; then
     echo "$foo is a directory"
  else
     echo "$foo is not a file, nor directory"
  fi
done
Array[] 
#!/bin/bash
admins=(aaa@example.com bbb@example.com ccc@example.com) 
 
For Each
for name in ${admins[@]}; do
  mail -s "Log file" $name < $mylog
done
 
IF判斷式

#!/bin/sh
if grep $1 /etc/passwd > /dev/null
then
  echo "found $1"
else
  echo "didn't find $1"
fi
 
巢狀IF
  
#!/bin/sh
if grep $1 /etc/passwd > /dev/null
then
  echo "found $1 in /etc/passwd"
elif grep $1 /etc/greoup > /dev/null
then
  echo "found $1 in /etc/group"
else
  echo "didn't find $1"
fi 
 
Testing 判斷式
Testing 判斷式通常與if-then-else一起互用, 以便發揮其效果.
先從一個最簡單的例子看起 :

#!/bin/sh
if [ -f /etc/passwd ]; then
   echo "/etc/passwd is a file"
else
   echo "PANIC : /etc/passwd is not a file!!"
fi 

注意: 中括號 []  內每個單元必須以空白分隔 變數與括號也要分開


test     true if ....

[ string1 = string2 ] string1 and string2 are equal [ string1 != string2 ] string1 and string2 are not equal [ string1 \< string2 ] string1 is lexically less than string2 (e.g. 'a' is less than 'b') [ string1 \> string2 ] string1 is lexically greater than string2 (e.g. 'b' is greater than 'a') [ -z string ] string is zero (e.g. a empty string) [ -n string ] string is nonzero (e.g. a VAR string) [ -e file ] file exists [ -f file ] file is a file [ -d file ] file is a directory [ -c file ] file is a character device [ -b file ] file is a block device [ -p file ] file is a named pipe [ -s file ] file is not empty [ -k file ] file's sticky bit is set [ -S file ] file is a socket [ -L file ] file is a symbolic link [ -r file ] file is readable by user [ -w file ] file is writeable by user [ -x file ] file is executeable by user [ -O file ] file is owner by user [ -G file ] file is group owned by a greoup [ -u file ] file has its set user ID bit set [ -g file ] file has its group user ID bit set [ file1 -nt file2 ] file1 is newer than file2 [ file1 -ot file2 ] file1 is older than file2 [ file -ef file2 ] file1 is another name for file2 [ n1 -eq n2 ] true if integer n1 = integer n2 [ n1 -ne n2 ] true if integer n1 <> n2 [ n1 -gt n2 ] true if n1 > n2 [ n1 -ge n2 ] true if n1 >= n2 [ n1 -lt n2 ] true if n1 < n2 [ n1 -le n2 ] true if n1 <= n2

沒有留言:

張貼留言