Motorahead
Motorahead

Reputation: 75

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

Trying to dynamically capture a list of specific alias commands, and store for execution later in the script. I want to dynamically capture, since this script will run against multiple users on multiple servers with different commands. IE: server1 might have 'statcmd1', 2 and 3; while server2 will only have 'statcmd2'. There is more to it, but this is where I am stuck. I'm guessing something isnt right with how the array is being set? Maybe there is another way to do this.

Test:

#!/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 $2}'| awk -F '=' '{print $1}' | grep -F "stat"))

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

Execution:

[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

Execute Alias Commands Outside of Script Works:

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

Upvotes: 0

Views: 428

Answers (2)

hnicke
hnicke

Reputation: 602

From the bash manpage:

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).

Execute

shopt -s expand_aliases

before executing the commands - afterwards, all aliases are also available in the script.

Furthermore, due to the fact that alias expansion takes place before variable expansion, the line has to be evaluated twice with the help of 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 $2}'| awk -F '=' '{print $1}' | 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

Upvotes: 3

PesaThe
PesaThe

Reputation: 7499

According to Bash Reference Manual, alias expansion is performed prior to variable expansion. Therefore the expansion of $i is not even attempted to be expanded as an alias.

You can use functions instead. Command/function execution is performed after variable expansion. As a matter of fact, the manual also says:

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

Upvotes: 3

Related Questions