what are the differences between eval
and alias
commands?
Examples:
x=‘ls -d -l $HOME’
$x
eval $x
alias y=‘ls -l -d $HOME’
y
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityMostly semantics. While combining your command strings into variables is useful for scripting purposes, it isn't good for aliasing. One visible reason is completion - while various completion scripts, like bash_completion
might be able to deal with aliases (which sadly never happened to be my case), making them assume that variables are extendable to commands could make it somehow messy.
Second reason is alias
allows you to make command shortcuts without using any magic command nor character like $
to run them. This way the substitution is transparent and it allows to override default settings for some programs. One good example is ls
, which is often aliased as ls --color=auto
by default. Users don't have to know that to see colored output. Some distributions alias rm
and related commands as rm -i
, so they work in interactive mode and can prevent accidental removals.
Variables on the other hand may be useful for some uses that don't require mimicking binaries. A wide and good example is EDITOR
environmental variable. It makes it possible not only to run your favorite editor using $EDITOR
, but also makes other programs (which may not have access to shell) able to run it, taking it's value from their execution environment.
There might be some other things I'm not aware of, but the outcome is the same: those commands are to be used as they're intended.
Aliases are not to be used in scripts (disabled by default in non-interactive shells. You can even combine several aliases (like several strings for eval). But aliases don't give you the nice level of indirection which you get from the command line getting parsed twice:
text1=foo; text2=bar; text3=fubar
for((i=1;i<4;i++)); do
eval echo \$text${i}
done
I admit this could be done without eval (varname=text${i}; echo ${!varname}
). But when constructing commands I would always use eval.
shell-expand-line (M-C-e) works with neither without errors. :-)