How to make alias command work in bash script or bashrc file

set alias‘ for any command and the alias command will work fine on the interactive shell, whereas aliasing doesn’t work inside the script.

1. Interactive shell

# alias ls1='ls -lrt'
# ls1
total 0
-rw-r--r-- 1 root root 0 Oct 12 12:14 file1
-rw-r--r-- 1 root root 0 Oct 12 12:14 file2

2. Inside the script

# cat script.sh
#!/bin/bash
# Script to check the alias output
alias ls1='ls -lrt'
ls1
# chmod +x script.sh
# ./script.sh 
./script.sh: line 3: ls1: command not found

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt. It can be tested by adding the command “alias” to simple bash script and the script execution will not give the alias command, whereas on the interactive shell it will provide the available list of aliasing as shown in the above example.

From the man page of Bash :

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

Making alias work in bash script

The following approach can be used, for making alias command work in bash scripts. Variables can be used in the bash script to set the preferred options for any command and those variables can be referred in the later section of script to suffice the need of alias inside scripts.

Add the command ‘shopt -s expand_aliases’ at the start of the script to expand aliases and make alias command work in the bash script.

# cat script.sh
#!/bin/bash
# Script to check the alias output
shopt -s expand_aliases
alias ls1='ls -lrt'
ls1
# chmod +x script.sh
# ./script.sh
total 0
-rw-r--r-- 1 root root 0 Oct 12 12:14 file1
-rw-r--r-- 1 root root 0 Oct 12 12:14 file2
Related Post