咨询个小 bash 问题

2018-08-08 22:07:26 +08:00
 frmongo

问题

如下 bash 里,有一个随机的参数 inputString,然后我想写一堆条件,为了得到一个中文变量。 请问这种 if elif 的写法有其他的简略写法没有?否则感觉有点笨...

CODE

有一个${inputString} 

if [ ${inputString} == "111" ]; then
    cn="中文 1"
elif [ ${inputString} == "222" ]; then
    cn="中文 2"
elif [ ${inputString} == "333" ]; then
    cn="中文 3"
elif [ ${inputString} == "444" ]; then
    cn="中文 4"
elif [ ${inputString} == "555" ]; then
    cn="中文 5"
elif [ ${inputString} == "666" ]; then
    cn="中文 6"
else
    cn="错误的输入"
fi
echo ${cn}
1998 次点击
所在节点    Linux
5 条回复
GGGG430
2018-08-08 22:16:57 +08:00
do {
if [ ${inputString} == "111" ]; then
cn="中文 1"
break

if [ ${inputString} == "222" ]; then
cn="中文 2"
break

cn="错误的输入"
} while(false)

语法可能有错误, 但方式就是用 do()while(false) + break 实现
zbinlin
2018-08-08 22:24:35 +08:00
mmtromsb456
2018-08-08 22:38:33 +08:00
使用 case in 结构呗
case ${inputString} in
111)
cn="xxx"
;;
222)
cn="xxx"
;;
*)
cn="错误的输入"
;;
esac
tt0411
2018-08-08 22:44:10 +08:00
bash 是支持 hash 表的, 具体用法可以搜索;

也可用 awk, 比如

awk '$1 == "'$input_string'" {print $2}' <<EOF
111 中文 1
222 中文 2
333 中文 3
EOF
lihongjie0209
2018-08-09 12:01:27 +08:00
hash table 不知道 bash 有没有

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/478079

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX