An alias should effectively not (in general) do more than change the default options of a command. It is nothing more than simple text replacement on the command name. It can't do anything with arguments but pass them to the command it actually runs. So if you simply need to add an argument at the front of a single command, an alias will work. Common examples are
# Make ls output in color by default.
alias ls="ls --color=auto"
# make mv ask before overwriting a file by default
alias mv="mv -i"
A function should be used when you need to do something more complex than an alias but that wouldn't be of use on its own. For example, take this answer on a question I asked about changing grep
's default behavior depending on whether it's in a pipeline:
grep() {
if [[ -t 1 ]]; then
command grep -n "$@"
else
command grep "$@"
fi
}
It's a perfect example of a function because it is too complex for an alias (requiring different defaults based on a condition), but it's not something you'll need in a non-interactive script.
If you get too many functions or functions too big, put them into separate files in a hidden directory, and source them in your ~/.bashrc
:
if [ -d ~/.bash_functions ]; then
for file in ~/.bash_functions/*; do
. "$file"
done
fi
A script should stand on its own. It should have value as something that can be re-used, or used for more than one purpose.
After some testing, I have concluded the following:
- Aliases only work in interactive mode (add
-i
to the shebang).
- Aliases are not evaluated when they come from an interpreted source (in this case, the variable.
- You can get bash to use the alias with
eval $1
. Note that eval
ing anything created with a variable is dangerous, but since the whole point of the script requires arbitrary execution, I won't make too big a deal out of that.
From the bash man page:
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases shell option is set using shopt (see the description of
shopt under SHELL BUILTIN COMMANDS below).
So you could add shopt -s expand_aliases
instead of -i
.
Also,
Aliases are expanded when a command is read, not when it is executed.
Since variables are not expanded before the command is read, they will not be expanded further using the alias.
Best Answer
try this:
worked at least for me: