[英]Loop over bash aliases and run commands in script
我正在尝试创建一个具有别名列表的 bash 脚本并在我的脚本中运行它们。 (这只是一个简化的例子,但它解释了这种情况)。
应该发生的是我遍历我的别名并且脚本一一执行它们。
别名列表.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
这是我得到的第一个命令。/test_alias_loop.sh: line 12: al1: command not found
但是,当我这样做的时候
al1
命令运行,我得到了当前目录的 ls 。
如何遍历别名命令列表并在我的脚本中实际运行它们?
如果目的是检查以确保别名有效,则在处理后将它们传送到 bash 似乎有效。
$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
给出:
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
您的问题可以简化为以下示例:
alias xx=echo
foo=xx;
$foo text.
你会得到bash: xx: command not found 。 似乎命令在变量扩展之后不再被视为可能的别名。 这可以从bash手册页中的以下句子中解释:
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.
虽然它没有明确说明,但我认为命令中的第一个单词在任何其他替换之前都经过测试。
但是,即使您找到解决此问题的方法,您的脚本也无法正常工作,因为 - 正如手册页所说 - :
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases shell option is set using shopt.
因此,要在脚本中使用别名,您必须明确打开此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.