Shell ternary operation (detailed case)

  • Common ternary operations in other grammars:

    表达式 ? 表达式 : 表达式 ;
    
  • shellThere is also a similar way in :

    command1 && command2 || command3
    

    If commandis a series of combinations, you can use { }to commandsenclose. Note: If the code block is used in a function,  { } the last one must be ;

    command1 && {
          
           command2_1; command2_2; command2_3; } || {
          
           command3_1; command3_3; command3_3; }
    
  • example

    #!/bin/bash
    
    res="mp-weixin"
    
    iswx=$([[ $res =~ "weixin" ]] && echo 1 || echo 0)
    
    echo "$iswx"
    
    # fileName 文件不存在,则退出,就可以按照下面方式执行
    [ -e $fileName ] || {
          
           echo -e "fileName Not existed!"; exit 1; }
    
    #也或者可以增加一些 log 打印信息
    [ -e $fileName ] && echo -e "$fileName existed" || {
          
           echo -e "$fileName Not existed!"; exit 1; }
    
    #多个命令集合的组合
    [ -e $fileName ] && echo -e "$fileName existed"; ehco -e "Other Necessary Information" || {
          
           echo -e "$fileName Not existed!"; exit 1; }
    [ -e $fileName ] && {
          
           echo -e "$fileName existed"; ehco -e "Other Necessary Information"; } || {
          
           echo -e "$fileName Not existed!"; exit 1; }
    
    #读取IP地址,若为空,则使用默认IP,否则使用新的IP地址
    read -p "Please input Management IP (Default is $DEFAULT_IP): " MGMT_IP 
    [[ -z $MGMT_IP ]] && {
          
           MGMT_IP=$DEFAULT_IP; echo -e "Using default IP $MGMT_IP\n" ;} || DEFAULT_IP=$MGMT_IP
    

Guess you like

Origin blog.csdn.net/zz00008888/article/details/132297103