将别名命令名称捕获到数组中。然后在 For 循环中执行每个

Capture Alias Command Names into Array. Then Execute each in a For Loop

正在尝试动态捕获特定别名命令的列表,并存储以便稍后在脚本中执行。我想动态捕获,因为此脚本将 运行 针对多个服务器上的多个用户使用不同的命令。 IE:server1 可能有 'statcmd1'、2 和 3;而 server2 将只有 'statcmd2'。还有更多,但这就是我被困的地方。我猜数组的设置方式不对?也许还有另一种方法可以做到这一点。

测试:

#!/bin/bash

source $HOME/.bash_profile    #Aliases are set in here

# Capture the set aliases into array. It will omit the actual command and only pick up the alias name.
ALL_STAT=($(alias | grep "control.sh" | awk '{print }'| awk -F '=' '{print }' | grep -F "stat"))

#Execute the status of all elements listed in the array
for i in ${ALL_STAT[@]}; do $i; done

执行:

[user@server]$ ./test.sh
./test.sh: line 16: statcmd1: command not found
./test.sh: line 16: statcmd2: command not found
./test.sh: line 16: statcmd3: command not found

在脚本工作之外执行别名命令:

[user@server]$ statcmd1
RUNNING
[user@server]$ statcmd2
RUNNING
[user@server]$ statcmd3
RUNNING

根据Bash Reference Manual,别名扩展在变量扩展之前执行。因此 $i 的扩展甚至都没有尝试作为别名进行扩展。

您可以改用函数。 Command/function 执行 变量扩展之后。事实上,manual 也表示:

For almost every purpose, shell functions are preferred over aliases.

来自 bash 联机帮助页:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).

执行

shopt -s expand_aliases

在执行命令之前 - 之后,脚本中也可以使用所有别名。

此外,由于别名扩展发生在变量扩展之前,因此必须借助 eval:

对该行求值两次
#!/bin/bash

source $HOME/.bash_profile    #Aliases are set in here

# Capture the set aliases into array. It will omit the actual command and only pick up the alias name.
ALL_STAT=($(alias | grep "control.sh" | awk '{print }'| awk -F '=' '{print }' | grep -F "stat"))

shopt -s expand_aliases
#Execute the status of all elements listed in the array
for i in ${ALL_STAT[@]}
do
    eval "$i"
done