Bash:if vs.case

Bash:if vs.case,bash,Bash,下面我使用if语句和case语句来安排下面参数的顺序,以简化我使用rsync进行的重复键入。对于下面的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/" rem

下面我使用
if
语句和
case
语句来安排下面参数的顺序,以简化我使用rsync进行的重复键入。对于下面的
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

case
语句将在此处生成更可读、更紧凑的代码:

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

case
语句将在此处生成更可读、更紧凑的代码:

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

您可以连接$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

您可以连接$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

没有理由同时处理这两个问题,也绝对没有理由使用
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

没有理由同时处理这两个问题,也绝对没有理由使用
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

您可以连接$1和$2来打开它。您可以连接$1和$2来打开它。在数组中生成命令也比在变量中生成命令更好。在数组中生成命令也比在变量中生成命令更好。