Home > Software engineering >  obtain dynamically executable path depending on script variable avoiding many ifs
obtain dynamically executable path depending on script variable avoiding many ifs

Time:09-23

I want to run determined executable depending on a variable of my script cur_num

I have this code, where the paths are "random", meaning they have nothing to do with the secuential cur_num:

run() {
    if [ $cur_num = "0" ]
        then ~/pathDirName0/execFile0 
    elif [ $cur_num = "1" ] 
        then ~/pathDirName1/execFile1
    elif [ $cur_num = "2" ] 
        then ~/pathDirName2/execFile2 
    elif [ $cur_num = "3" ] 
        then ~/pathDirName3/execFile3
    elif [ $cur_num = "4" ] 
        then ~/pathDirName4/execFile4
    fi
}

In case there are lots more of cases, that resulys in a very long if - elif statement. As there are no enums in bash to build the cur_num- path relation, is there a cleaner way to obtain the desired path dynamically instead of with lots of ifs?

CodePudding user response:

Try case

case $cur_num in
      0) ~/pathDirName0/execFile0;;
      1) ~/pathDirName1/execFile1;;
      2) ~/pathDirName2/execFile2;;
      ...
esac

CodePudding user response:

set allows you to create arrays in a portable manner, so you can use that to create an ordered array:

set -- ~/pathDirName0/execFile0 ~/pathDirName1/execFile1 ~/pathDirName2/execFile2 ~/pathDirName3/execFile3 ~/pathDirName4/execFile4

Then to access these items via an index you do $x where x is the index of the item.

Now your code would look something like this:

run() {
    original="$@"

    : $((cur_num =1)) # Positional param indexing starts from 1

    set -- ~/pathDirName0/execFile0 ~/pathDirName1/execFile1 \
           ~/pathDirName2/execFile2 ~/pathDirName3/execFile3 \
           ~/pathDirName4/execFile4

    eval "$"$cur_num"" # cur_num = 1, accesses $1 == execFile0

    set -- $original # Restore original args
}

A method that is both less and more hacky that would work for indexes above 9 and not mess with the original positional parameters nor use eval

run() {
    count=0

    for item in "$@"; do
        [ "$count" = "$cur_num" ] && {
            "$item"
            return        
        }

        : "$((count =1))"
    done

    echo "No item found at index '$cur_num'"
}

cur_num="$1" # Assuming first arg of script.

run ~/pathDirName0/execFile0 ~/pathDirName1/execFile1 \
    ~/pathDirName2/execFile2 ~/pathDirName3/execFile3 \
    ~/pathDirName4/execFile4
  •  Tags:  
  • bash
  • Related