【问题标题】:Loop over bash aliases and run commands in script循环 bash 别名并在脚本中运行命令
【发布时间】:2020-09-04 23:43:00
【问题描述】:

我正在尝试创建一个包含别名列表的 bash 脚本并在我的脚本中运行它们。 (这只是一个简化的例子,但它解释了这种情况)。

应该发生的是我遍历我的别名并且脚本一一执行它们。

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

这是我第一个命令得到的 ./test_alias_loop.sh: line 12: al1: command not found

但是,当我这样做的时候

al1

命令运行,我得到当前目录的 ls。

如何遍历别名命令列表并在我的脚本中实际运行它们?

【问题讨论】:

    标签: bash macos terminal alias


    【解决方案1】:

    如果目的是检查以确保别名有效,那么在处理后将它们传送到 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 ls1 ls2 ls3。人们永远不知道可能潜伏着什么杂散别名。
    【解决方案2】:

    你的问题可以简化为这个例子:

    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.
    

    因此,要在脚本中使用别名,您必须明确启用此功能。

    【讨论】:

      猜你喜欢
      • 2014-10-04
      • 2021-08-27
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多