Set and use alias within Bash script
Bash scripts by default ignore aliases, unless the command
shopt -s expand_aliases
has been used before the aliased command. This is typically a good thing, as if one has set in ~/.bash_aliases something like
alias mv="mv -v"
any script using mv
could produce extremely lengthy and verbose output when installing a program for example.
However, sometimes a user has multiple versions of a program installed in directories in $PATH
and for whatever reason cannot use update-alternatives
to make the desired one the default.
You really should use
update-alternatives
instead whenever possible as this method described here is not as robust.
Because we are not source
ing the Bash script, the alias scope is only within the Bash script itself.
That is, once the script is done, the alias disappears.
Let’s say your IT department has installed CMake 2 as /usr/bin/cmake2
and CMake 3 as /usr/bin/cmake3
.
They really shouldn’t install it like that, but suppose they did anyway.
If a script needs CMake 3.x, and you can’t use update-alternatives
, do within the Bash script:
shopt -s expand_aliases
alias cmake=/usr/bin/cmake3
Again, we stress this is not general or robust, so only do this as a last resort.
sudo
is not required for
update-alternatives
.
Put the softlinks under $HOME/.local/bin and put that on your $PATH as a much better choice.