Is there an elegant way to store and evaluate return values in bash scripts?

后端 未结 6 2109
傲寒
傲寒 2020-12-01 20:03

I have a rather complex series of commands in bash that ends up returning a meaningful exit code. Various places later in the script need to branch conditionally on whether

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 20:29

    Why don't you set flags for the stuff that needs to happen later?

    cheeseballs=false
    nachos=false
    guppies=false
    
    command
    case $? in
        42) cheeseballs=true ;;
        17 | 31) cheeseballs=true; nachos=true; guppies=true;;
        66) guppies=true; echo "Bingo!";;
    esac
    
    $cheeseballs && java -crash -burn
    $nachos && python ./tex.py --mex
    if $guppies; then
        aquarium --light=blue --door=hidden --decor=squid
    else
        echo SRY
    fi
    

    As pointed out by @CharlesDuffy in the comments, storing an actual command in a variable is slightly dubious, and vaguely triggers Bash FAQ #50 warnings; the code reads (slightly & IMHO) more naturally like this, but you have to be really careful that you have total control over the variables at all times. If you have the slightest doubt, perhaps just use string values and compare against the expected value at each junction.

    [ "$cheeseballs" = "true" ] && java -crash -burn
    

    etc etc; or you could refactor to some other implementation structure for the booleans (an associative array of options would make sense, but isn't portable to POSIX sh; a PATH-like string is flexible, but perhaps too unstructured).

提交回复
热议问题