IF ELSE声明

时间:2017-04-25 10:45:58

标签: bash if-statement syntax-error conditional

我想问一个问题“你想用什么格式?”,然后,根据答案是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'

4 个答案:

答案 0 :(得分:2)

我会使用更长的时间,但用户友好的变体更多:

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退出......
  • 处理错误(错误输入)的答案并再次询问......

答案 1 :(得分:1)

#!/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语句。

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

答案 2 :(得分:1)

选项和参数应存储在数组中,而不是单个字符串。此外,$(function() { //Paste your functions inside this; }); 语句在这里会更简单。

case

答案 3 :(得分:0)

正确的语法是

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

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