简体   繁体   English

循环 bash 别名并在脚本中运行命令

[英]Loop over bash aliases and run commands in script

I'm trying to create a bash script which has a list of aliases and run them in my script.我正在尝试创建一个具有别名列表的 bash 脚本并在我的脚本中运行它们。 (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别名列表.sh

#!/bin/bash

alias al1="ls"
alias al2="ls ."
alias al3="ls .."

test_alias_loop.sh 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这是我得到的第一个命令。/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.命令运行,我得到了当前目录的 ls 。

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.如果目的是检查以确保别名有效,则在处理后将它们传送到 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

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 .你会得到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:这可以从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.

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.因此,要在脚本中使用别名,您必须明确打开此功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM