gpt4 book ai didi

bash - IF ELSE声明

转载 作者:行者123 更新时间:2023-12-03 08:04:25 25 4
gpt4 key购买 nike

我想问一个问题:“您想使用哪种格式?”,然后根据答案是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'

最佳答案

我会使用更长的时间,但是使用起来更加友好:

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?>

用户可以输入:
  • 对应编号
  • jsont_li或 jjsjson和xml的 xxml,xml的
  • h获取帮助
  • 退出的
  • q ...
  • 错误(类型错误)答案已处理并再次询问...
  • 关于bash - IF ELSE声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43608524/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com