Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
frmongo
V2EX  ›  Linux

咨询个小 bash 问题

  •  
  •   frmongo · Aug 8, 2018 · 2594 views
  •   You need to sign in to view this topic
    This topic created in 2907 days ago, the information mentioned may be changed or developed.

    问题

    如下 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 replies    2018-08-09 12:01:27 +08:00
    GGGG430
        1
    GGGG430  
       Aug 8, 2018   ❤️ 1
    do {
    if [ ${inputString} == "111" ]; then
    cn="中文 1"
    break

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

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

    语法可能有错误, 但方式就是用 do()while(false) + break 实现
    mmtromsb456
        3
    mmtromsb456  
       Aug 8, 2018
    使用 case in 结构呗
    case ${inputString} in
    111)
    cn="xxx"
    ;;
    222)
    cn="xxx"
    ;;
    *)
    cn="错误的输入"
    ;;
    esac
    tt0411
        4
    tt0411  
       Aug 8, 2018
    bash 是支持 hash 表的, 具体用法可以搜索;

    也可用 awk, 比如

    awk '$1 == "'$input_string'" {print $2}' <<EOF
    111 中文 1
    222 中文 2
    333 中文 3
    EOF
    lihongjie0209
        5
    lihongjie0209  
       Aug 9, 2018
    hash table 不知道 bash 有没有
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2787 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 14:25 · PVG 22:25 · LAX 07:25 · JFK 10:25
    ♥ Do have faith in what you're doing.