如果 ELSE 语句

IF ELSE statement

我想问问题"What format do you want to use?",然后,根据答案是xml还是json,打印相应的输出。但是,如果它不是 xmljson,则代码结束。

代码:

#!/bin/bash
read -r -e -p "What format do you want to use? json/xml?: " format

if [[ "${format,,}" == "json" ]]; then
    curl=$curl"\"\Content-Type: application/json\"\
else [[ "${format,,}" == "xml" ]]; then
    curl=$curl"\"\Content-Type: application/xml\"\
elif [[ "${format,,}" == "no" ]]; then
  echo "Goodbye, you must specify a format to use Rest"
else 
  echo "Unknown"
  exit 0
fi
echo $curl

我尝试 运行 时收到此错误:

[root@osprey groups]# ./test3
What format do you want to use? json/xml?: xml
./test3: line 8: syntax error near unexpected token `then'
./test3: line 8: `elif [[ "${format,,}" == "no" ]]; then'

正确的语法是

if ...
elif ...
else ...
fi

else 后面必须跟命令,而不是条件和 ; then.

#!/bin/bash
read -r -e -p "What format do you want to use? json/xml?: " format

if [[ "${format,,}" == "json" ]]; then
    curl=$curl"\"Content-Type: application/json\""
elif [[ "${format,,}" == "xml" ]]; then
    curl=$curl"\"Content-Type: application/xml\""
elif [[ "${format,,}" == "no" ]]; then
  echo "Goodbye, you must specify a format to use Rest"
else 
  echo "Unknown"
  exit 0
fi
echo $curl

应该可以。如果不是,则问题不在于 if/else 语句。

编辑:发现问题。这是引号的错误使用。我试图修复它,所以上面的现在应该可以工作了。

选项和参数应存储在数组中,而不是单个字符串中。此外,case 语句在这里会更简单。

#!/bin/bash

curl_opts=()
read -r -e -p "What format do you want to use? json/xml?: " format

shopt -s nocasematch
case $format in
  json) curl_opts+=(-H "Content-Type: application/json") ;;
  xml)  curl_opts+=(-H "Content-Type: application/xml") ;;
  no)  printf 'Goodbye, you must specify a format to use Rest\n' >&2
       exit 1
       ;;
   *) printf 'Unknown format %s, exiting\n' "$format" >&2
      exit 1
      ;;
esac

curl "${curl_opts[@]}" ...

我会使用更长一点但对用户更友好的变体:

err() { echo "$@" >&2; return 1; }

show_help() {
cat - >&2 <<EOF
You must specify a format to use Rest because bla bla...
EOF
}

select_format() {
    PS3="Select the format do you want to use?> "
    select ans in json xml "quit program"; do
        case "$REPLY" in
            [0-9]*) answer=$ans;;
            *) answer=$REPLY;;
        esac
        case "${answer,,}" in
            '') ;;
            j|js|json) echo '-H "Content-Type: application/json"' ; return 0 ;;
            x|xml)     echo '-H "Content-Type: application/xml"'  ; return 0 ;;
            q|quit*)   err "Bye..." ; return 1;;
            h|help)  show_help ;;
            *) err "Unknown format $answer" ;;
        esac
    done
    [[ "$answer" ]] || return 1 #handles EOF (ctrl-D)
}

curl_args=()
curl_args+=( $(select_format) ) || exit 1
echo curl "${curl_args[@]}"

显示菜单:

1) json
2) xml
3) quit program
Select the format do you want to use?> 

并且用户可以输入:

  • 要么对应号码
  • jjsjson为json和xxml为xml
  • h求助
  • q退出...
  • 处理不正确(打错)的答案并再次询问...