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?
The Bash alias command allows a string to be substituted when it is used as the first word of a command line. The shell maintains a list of aliases that may be set and unset with the Bash alias and unalias builtin commands.
An alias is a way of shortening a command. (They are only used in interactive shells and not in scripts — this is one of the very few differences between a script and an interactive shell.)
These are positional arguments of the script. Executing ./script.sh Hello World. Will make $0 = ./script.sh $1 = Hello $2 = World. Note. If you execute ./script.sh , $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh .
From the bash
man page:
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases
shell option is set usingshopt
(see the description ofshopt
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With