V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
frmongo
V2EX  ›  Linux

咨询个小 bash 问题

  •  
  •   frmongo · 2018-08-08 22:07:26 +08:00 · 1983 次点击
    这是一个创建于 2059 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题

    如下 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}
    
    5 条回复    2018-08-09 12:01:27 +08:00
    GGGG430
        1
    GGGG430  
       2018-08-08 22:16:57 +08:00   ❤️ 1
    do {
    if [ ${inputString} == "111" ]; then
    cn="中文 1"
    break

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

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

    语法可能有错误, 但方式就是用 do()while(false) + break 实现
    zbinlin
        2
    zbinlin  
       2018-08-08 22:24:35 +08:00
    mmtromsb456
        3
    mmtromsb456  
       2018-08-08 22:38:33 +08:00
    使用 case in 结构呗
    case ${inputString} in
    111)
    cn="xxx"
    ;;
    222)
    cn="xxx"
    ;;
    *)
    cn="错误的输入"
    ;;
    esac
    tt0411
        4
    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
        5
    lihongjie0209  
       2018-08-09 12:01:27 +08:00
    hash table 不知道 bash 有没有
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5361 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 07:58 · PVG 15:58 · LAX 00:58 · JFK 03:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.