2017-01-09 1 views
1

以下、私はifステートメントとcaseステートメントを使用して、rsyncで繰り返し入力するのを簡単にするために、以下の私の議論の順序を整理します。以下のifブロックのcaseステートメントは賢明でしょうか?もしそうなら、どうですか?Bash:if対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

はそれに切り替えるために$ 1、$ 2連結Youcould。 – 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

2つを処理する理由はない、とは絶対にない理由は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