Bash When to use eval Using Eval with Getopt


Example

While eval may not be needed for a pop like function, it is however required whenever you use getopt:

Consider the following function that accepts -h as an option:

f()
{
    local __me__="${FUNCNAME[0]}"
    local argv="$(getopt -o 'h' -n $__me__ -- "$@")"

    eval set -- "$argv"
    
    while :; do
        case "$1" in
            -h)
              echo "LOLOLOLOL"
              return 0
              ;;
            --)
              shift
              break
              ;;
    done
    
    echo "$@"
}

Without eval set -- "$argv" generates -h -- instead of the desired (-h --) and subsequently enters an infinite loop because -h -- doesn't match -- or -h.