How do create an alias in shell scripts?

alias, bash, shell

Solution

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 this should work:

#!/bin/bash
shopt -s expand_aliases
alias I_am_only_ls_alias=ls
I_am_only_ls_alias

Scripts usually use functions, not aliases.

Problem

Definin an alias on Linux system is very simple. From the following example we see that: the `I_am_only_ls_alias` alias command gives us the output as `ls` command ``` # alias I_am_only_ls_alias=ls # I_am_only_ls_alias ``` Output: ``` file file1 ``` But when I trying to do the same in bash script (`define alias I_am_only_ls_alias`), I get `I_am_only_ls_alias: command not found`. Example of my bash script: `alias_test.bash` ``` #!/bin/bash alias I_am_only_ls_alias=ls I_am_only_ls_alias ``` Run the bash script - `alias_test.bash` ``` /tmp/alias_test.bash ``` Output: ``` /tmp/: line 88: I_am_only_ls_alias: command not found ``` So, first I want to ask: Why doesn't bash recognize the command `I_am_only_ls_alias` as an alias? And what do I need to do in order to define aliases inside a bash script? Is it possible?

Original source

Related problems