2017-01-09 52 views
1

下面我使用if語句和case語句來安排我的參數在下面的順序,以減輕我對rsync做的重複輸入。 case陳述對於下面的if塊更明智嗎?如果是這樣,怎麼樣?Bash:if vs. case

#!/bin/bash 

rsync="rsync -vrtzhP --delete" 
localmus=" /cygdrive/c/Users/user/Music/Zune/" 
remotemus=" 10.252.252.254::Zune/" 
localcal=" /cygdrive/c/Users/user/calibre/" 
remotecal=" 10.252.252.254::calibre/" 
dry=" -n" 

if [ $1 == "zune" ] && [ $2 == "tohere" ] 
then 
    toex=$rsync$remotemus$localmus 
fi 

if [ $1 == "zune" ] && [ $2 == "tothere" ] 
then 
    toex=$rsync$localmus$remotemus 
fi 

if [ $1 == "calibre" ] && [ $2 == "tohere" ] 
then 
    toex=$rsync$remotecal$localcal 
fi 

if [ $1 == "calibre" ] && [ $2 == "tothere" ] 
then 
    toex=$rsync$localcal$remotecal 
fi 


if [[ $3 == "dry" ]] 
then 
    toex=$toex$dry 
fi 

echo 
echo $toex 
echo 
echo "Execute? y/n: " 
read answer 
case $answer in 
    y) 
     eval $toex 
    ;; 
    n) 
     echo NO! 
    ;; 
esac 
+0

Youcould串聯了$ 1,$ 2就可以切換。 – eckes

回答

1

一個case聲明將在這裏生產更具可讀性和緊湊的代碼:

case "$1-$2" in 
"zune-tohere") 
    toex="$rsync$remotemus$localmus" 
    ;; 
... 
esac 
+1

最好在數組中構建命令,而不是通過連接變量。 –

3

你可以串連了$ 1,$ 2就可以切換。

case "$1 $2" in 
"zune toHere") 
    toex=$rsync$localmus$remotemus 
    ;; 
"calibre toHere") 
    toex=$rsync$remotecal$localcal 
    ;; 
*) 
    echo "Unknown command $1 $2" 
    exit 2 
    ;; 
esac 
0

沒有理由來處理兩者結合起來,並絕對沒有理由使用eval

remote=10.252.252.254:: 
local=/cygdrive/c/Users/user/ 

do_rsync() { 
    rsync -vrtzhP --delete "$1" "$2" 
} 

case $1 in 
    zune) 
    remote+=Zune/ 
    local+=/Music/Zune 
    ;; 
    calibre) 
    remote+=calibre/ 
    local+=/calibre 
    ;; 
    *) echo "Unknown transfer type: $1" >&2 
    return 1 
    ;; 
esac 

case $2 in 
    tohere) 
    do_rsync "$remote" "$local" ;; 
    tothere) 
    do_rsync "$local" "$remote" ;; 
    *) echo "Unknown transfer direction: $2" >&2 
    return 1 
esac