I'm trying to create a bash script which has a list of aliases and run them in my script. (This is just a simplified example, but it explains the situation).
What should happen is I loop over my aliases and the script executes them one by one.
alias_list.sh
#!/bin/bash
alias al1="ls"
alias al2="ls ."
alias al3="ls .."
test_alias_loop.sh
#!/bin/bash -i
# Expand aliases
shopt -s expand_aliases
source ~/Documents/test_ssh_bash/scripts/alias_list.sh
# Exists just to get a list of aliases, proper version gets aliases from bash command
aliases=$(printf "al1\nal2\nal3\n\n")
for ssh_alias in $aliases; do
echo "$ssh_alias"
$ssh_alias
done
This is what I get for the first command./test_alias_loop.sh: line 12: al1: command not found
But, when I just do
al1
The command runs and I get an ls of my current directory.
How can I loop over a list of alias commands and actually run them in my script?
If the intent is to check to make sure the aliases are valid, then piping them to bash after processing seems to work.
$alias ls1='ls 1'
$alias ls2='ls 2'
$alias ls3='ls 3'
$alias |
while read -r line ; do
echo "$line" |
perl -pe 's/.*?=//' |
xargs
done | bash
Gives:
ls: cannot access '1': No such file or directory
ls: cannot access '2': No such file or directory
ls: cannot access '3': No such file or directory
Your problem can be simplified to this example:
alias xx=echo
foo=xx;
$foo text.
You will get bash: xx: command not found . It seems that commands, after variable expansion, are not treated as possible aliases anymore. This can be explained from the following sentence taken from the bash man page:
Aliases allow a string to be substituted for a word when it is used as the
first word of a simple command.... The first word of each simple command, if
unquoted, is checked to see if it has an alias.
While it does not explicitly say so, I take it that the first word in the command is tested before any other substitution.
But even if you find a way around this problem, your script would not work, because - as the man page says -:
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases shell option is set using shopt.
So to use aliases in your script, you have to explicitly turn on this feature.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.