2009-07-30

【L】Shell Script : 將程式 SYNC 到開發或上線區

這算是我第一隻 Shell Script 吧。

但也只是簡單的將程式 Sync 到別台 Server 而以。

內容如下:

#!/bin/sh
src_folder="/root/www_src"
des_folder="/home/www"
o_webs="1 2 3 4 5"
o_cmd='rsync -rltvp -e "ssh -l root" --exclude ".svn"'
s_webs="9"
s_cmd='rsync -rltv -e "ssh -l root" --exclude ".svn"'

sync_action(){
  if [ $action = 'Stage' ]; then
    webs=$s_webs;
    cmd=$s_cmd;
  elif [ $action = 'Online' ]; then
    webs=$o_webs;
    cmd=$o_cmd;
  fi
  
  echo -n "** Sync to $action? [Y/N] ** : "
  read yes_no
  case "$yes_no" in
    [yY]*)
      echo "Sync to ${action}, Start ......"
      echo '----------------------------------------'
      for web in $webs
      do
        echo "Sync to www-${web}"
        echo '>>>>>>>>>>>>>>>>>>>>'
        eval $cmd ${src_folder}/www/ www-${web}:${des_folder}/www/
      done
      ;;
    [nN]*)
      echo "Sync to ${action}, Cancel ......"
      ;;
    *)
      echo 'You should Answer Y/N'
      echo 'bye~~'
      ;;
  esac
}

# 必須要為 root 才可以使用
if [ "$(id -u)" != "0" ]; then
   echo "You must run the script as root." 1>&2
   exit 1
fi

# 主程式
echo -n 'Sync to -- Stage(S) Online(O) Cancel(C) -- : '
read action
case "$action" in
  [sS]*)
    action='Stage';
    echo '========== STAGE =========='
    sync_action
    ;;
  [oO]*)
    action='Online';
    echo '========== online =========='
    sync_action
    ;;
  [cC]*)
    echo 'bye!!'
    ;;
  *)
    echo '... bye!!'
    ;;
esac
exit 0

PS.
一般來說應該直接$cmd bala bala 就好了,為什麼前面還要用 eval 哩,因為在$cmd裡面有【"】如果直接執行會出現錯誤訊息" Missing trailing-" in remote-shell command. "

0 comments:

張貼留言