1

I am trying to display which apps is deployed in each host. Using a bash script I had some success except I want to replace the following "hostname" part with the actual host name stored under the ${i} variable. I can't just substitute it because I cannot put a curly bracket inside another. EVEN if I can do it, I am still having trouble as ${i} will be replaced by the result of ls. How do I fix this?

hosts=(usa1 london2)
for i in ${hosts[@]}; do
    echo ---${i}---
    ssh ttoleung@${i} ls /apps | awk '{ printf("%s:%s\n", "hostname", $0) }'
done

Current output, based on code fragment above:

---usa01---
hostname:E2.gui
hostname:E1.server
---london2---
hostname:E1.gui

Desired output:

---usa01---
usa01:E2.gui
usa01:E1.server
---london2---
london2:E1.gui
ArMonk
  • 366
  • 6
  • 13

2 Answers2

1

As an intro note, it is not a safe expand array names without double quotes unless for obvious reasons because doing so would split quoted strings in array that themselves have spaces

So change

for i in ${hosts[@]}; 

to

for i in "${hosts[@]}";  # Note the quoted array

Now, coming to your problem, you can pass bash variables to awk using its -v parameter. So change

ssh ttoleung@${i} ls /apps | awk '{ printf("%s:%s\n", "hostname", $0) }'

to

ssh ttoleung@${i} ls /apps | awk -v hname="${i}" '{ printf("%s:%s\n", hname, $0) }'

Here we pass shell parameter ${i} to awk variable hname.

Side Note: Don't parse ls output for the reasons mentioned [ here ]. In your case though, it doesn't make much of a difference.

sjsam
  • 21,411
  • 5
  • 55
  • 102
1

Replace:

awk '{ printf("%s:%s\n", "hostname", $0) }'

With:

awk -v h="$i" '{ printf("%s:%s\n", h, $0) }'

-v h="$i" tells awk to create an awk variable h and assign to it the value of the shell variable $i.

Aside: we used h="$i" rather than h=$i because it is good practice to put shell variables inside double-quotes unless you want the shell to perform word-splitting and pathname expansion.

John1024
  • 109,961
  • 14
  • 137
  • 171