3

I have been trying to make aliases work in bash shell. Now, let's say I do alias yum='yum -v' in my shell. It works when I run the run the command from CLI. But when I run a script it doesn't have any effect. How can I make the aliases work across the shell?

Pensu
  • 3,263
  • 10
  • 46
  • 71

2 Answers2

2

In bash, you can export functions, so if you do:

yum() { command yum -v "$@"; }
export -f yum

Then the 'alias' for yum will persist in subshells. Note that functions are almost always preferred to aliases, and (from the bash man page) "For almost every purpose, aliases are superseded by shell functions.". I believe the initial clause 'For almost every purpose' is merely hyberbole and that 'almost' can be safely omitted.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

From the bash manpage:

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).

As a result, you need to do the following inside your script.:

shopt -s expand_aliases

You will also need to source your file with aliases (.bashrc,.bash_profile,.bash_login etc).

shopt -s expand_aliases
source /path/to/alias/file

Please note that using alias inside your shell script will make it less portable as it will break when ran on environment that do not have your aliases.

jaypal singh
  • 74,723
  • 23
  • 102
  • 147