"why should eval be avoided in bash, and what should i use instead?" Code Answer


there's more to this problem than meets the eye. we'll start with the obvious: eval has the potential to execute "dirty" data. dirty data is any data that has not been rewritten as safe-for-use-in-situation-xyz; in our case, it's any string that has not been formatted so as to be safe for evaluation.

sanitizing data appears easy at first glance. assuming we're throwing around a list of options, bash already provides a great way to sanitize individual elements, and another way to sanitize the entire array as a single string:

function println
    # send each element as a separate argument, starting with the second element.
    # arguments to printf:
    #   1 -> "$1n"
    #   2 -> "$2"
    #   3 -> "$3"
    #   4 -> "$4"
    #   etc.

    printf "$1n" "${@:2}"

function error
    # send the first element as one argument, and the rest of the elements as a combined argument.
    # arguments to println:
    #   1 -> 'e[31merror (%d): %se[m'
    #   2 -> "$1"
    #   3 -> "${*:2}"

    println 'e[31merror (%d): %se[m' "$1" "${*:2}"
    exit "$1"

# this...
error 1234 something went wrong.
# and this...
error 1234 'something went wrong.'
# result in the same output (as long as $ifs has not been modified).

now say we want to add an option to redirect output as an argument to println. we could, of course, just redirect the output of println on each call, but for the sake of example, we're not going to do that. we'll need to use eval, since variables can't be used to redirect output.

function println
    eval printf "$2n" "${@:3}" $1

function error
    println '>&2' 'e[31merror (%d): %se[m' "$1" "${*:2}"
    exit $1

error 1234 something went wrong.

looks good, right? problem is, eval parses twice the command line (in any shell). on the first pass of parsing one layer of quoting is removed. with quotes removed, some variable content gets executed.

we can fix this by letting the variable expansion take place within the eval. all we have to do is single-quote everything, leaving the double-quotes where they are. one exception: we have to expand the redirection prior to eval, so that has to stay outside of the quotes:

function println
    eval 'printf "$2n" "${@:3}"' $1

function error
    println '&2' 'e[31merror (%d): %se[m' "$1" "${*:2}"
    exit $1

error 1234 something went wrong.

this should work. it's also safe as long as $1 in println is never dirty.

now hold on just a moment: i use that same unquoted syntax that we used originally with sudo all of the time! why does it work there, and not here? why did we have to single-quote everything? sudo is a bit more modern: it knows to enclose in quotes each argument that it receives, though that is an over-simplification. eval simply concatenates everything.

unfortunately, there is no drop-in replacement for eval that treats arguments like sudo does, as eval is a shell built-in; this is important, as it takes on the environment and scope of the surrounding code when it executes, rather than creating a new stack and scope like a function does.

eval alternatives

specific use cases often have viable alternatives to eval. here's a handy list. command represents what you would normally send to eval; substitute in whatever you please.


a simple colon is a no-op in bash:


create a sub-shell

( command )   # standard notation

execute output of a command

never rely on an external command. you should always be in control of the return value. put these on their own lines:

$(command)   # preferred
`command`    # old: should be avoided, and often considered deprecated

# nesting:
$(command1 "$(command2)")
`command "`command`"`  # careful:  only escapes $ and  with old style, and
                         # special case ` results in nesting.

redirection based on variable

in calling code, map &3 (or anything higher than &2) to your target:

exec 3<&0         # redirect from stdin
exec 3>&1         # redirect to stdout
exec 3>&2         # redirect to stderr
exec 3> /dev/null # don't save output anywhere
exec 3> file.txt  # redirect to file
exec 3> "$var"    # redirect to file stored in $var--only works for files!
exec 3<&0 4>&1    # input and output!

if it were a one-time call, you wouldn't have to redirect the entire shell:

func arg1 arg2 3>&2

within the function being called, redirect to &3:

command <&3       # redirect stdin
command >&3       # redirect stdout
command 2>&3      # redirect stderr
command &>&3      # redirect stdout and stderr
command 2>&1 >&3  # idem, but for older bash versions
command >&3 2>&1  # redirect stdout to &3, and stderr to stdout: order matters
command <&3 >&4   # input and output!

variable indirection


var='1 2 3'


eval "echo "$$ref""

why? if ref contains a double quote, this will break and open the code to exploits. it's possible to sanitize ref, but it's a waste of time when you have this:

echo "${!ref}"

that's right, bash has variable indirection built-in as of version 2. it gets a bit trickier than eval if you want to do something more complex:

# add to scenario:
var_2='4 5 6'

# we could use:
local ref="${ref}_2"
echo "${!ref}"

# versus the bash < 2 method, which might be simpler to those accustomed to eval:
eval "echo "$${ref}_2""

regardless, the new method is more intuitive, though it might not seem that way to experienced programmed who are used to eval.

associative arrays

associative arrays are implemented intrinsically in bash 4. one caveat: they must be created using declare.

declare -a var   # local
declare -ga var  # global

# use spaces between parentheses and contents; i've heard reports of subtle bugs
# on some versions when they are omitted having to do with spaces in keys.
declare -a var=( ['']='a' [0]='1' ['duck']='quack' )

var+=( ['alpha']='beta' [2]=3 )  # combine arrays

var['cow']='moo'  # set a single element
unset var['cow']  # unset a single element

unset var     # unset an entire array
unset var[@]  # unset an entire array
unset var[*]  # unset each element with a key corresponding to a file in the
              # current directory; if * doesn't expand, unset the entire array

local keys=( "${!var[@]}" )  # get all of the keys in var

in older versions of bash, you can use variable indirection:

var=( )  # this will store our keys.

# store a value with a simple key.
# you will need to declare it in a global scope to make it global prior to bash 4.
# in bash 4, use the -g option.
declare "var_$key"="$value"
# or, if your version is lacking +=
var=( "$var[@]" "$key" )

# recover a simple value.
local var_key="var_$key"       # the name of the variable that holds the value
local var_value="${!var_key}"  # the actual value--requires bash 2
# for < bash 2, eval is required for this method.  safe as long as $key is not dirty.
local var_value="`eval echo -n "$$var_value""

# if you don't need to enumerate the indices quickly, and you're on bash 2+, this
# can be cut down to one line per operation:
declare "var_$key"="$value"                         # store
echo "`var_key="var_$key" echo -n "${!var_key}"`"   # retrieve

# if you're using more complex values, you'll need to hash your keys:
function mkkey
    local key="`mkpasswd -5r0 "$1" 00000000`"
    echo -n "${key##*$}"

local var_key="var_`mkkey "$key"`"
# ...
By Maaz on August 21 2022

Answers related to “why should eval be avoided in bash, and what should i use instead?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.