• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

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

by admin

‘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

Filed Under: Linux

Some more articles you might also be interested in …

  1. “az upgrade” Command Examples (Upgrade Azure CLI and Extensions)
  2. lsblk Command Examples in Linux
  3. ansible-vault – Encrypts & decrypts values, data structures and files within Ansible projects
  4. helix Command Examples
  5. check-support-status: Command Examples in Linux
  6. vnstat Command Examples in Linux
  7. a2disconf Command Examples in Linux
  8. man Command Examples in Linux
  9. “git ls-remote” Command Examples
  10. fprintd-list Command Examples in Linux

You May Also Like

Primary Sidebar

Recent Posts

  • Vanilla OS 2 Released: A New Era for Linux Enthusiasts
  • mk Command Examples
  • mixxx Command Examples
  • mix Command Examples

© 2025 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright