2

I'm working on a script, that should find certain disks and add hostname to them.

I'm using this for 40 servers with a for loop in bash

#!/bin/bash

for i in myservers{1..40}
    do ssh user@$i findmnt -o SIZE,TARGET -n -l |
            grep '1.8T\|1.6T\|1.7T' | 
            sed 's/^[ \t]*//' |
            cut -d ' ' -f 2 |
            awk -v HOSTNAME=$HOSTNAME '{print HOSTNAME ":" $0}'; done | 
    tee sorted.log

can you help out with the quoting here? It looks like awk gets piped (hostname) from localhost, not the remote server.

shaolin
  • 73
  • 1
  • 7

2 Answers2

0

Everything after the first pipe is running locally, not on the remote server.

Try quoting the entire pipeline to have it run on the remote server:

#!/bin/bash

for i in myservers{1..40}
    do ssh user@$i "findmnt -o SIZE,TARGET -n -l | 
        sed 's/^[ \t]*//' |
        cut -d ' ' -f 2 |
        awk -v HOSTNAME=\$HOSTNAME '{print HOSTNAME \":\" \$0}'" ;
done | tee sorted.log
rtx13
  • 2,580
  • 1
  • 6
  • 22
  • ... alternatively, just replace `HOSTNAME=$HOSTNAME` with `HOSTNAME=$i` in your original script. – rtx13 Mar 29 '20 at 16:16
0

This is a shorter version of your stuff:

findmnt -o SIZE,TARGET -n -l | 
awk -v HOSTNAME=$HOSTNAME '/M/{print HOSTNAME ":" $2}'

Applied to the above:

for i in myservers{1..40}
    do ssh user@$i   bash -c ' 
            findmnt -o SIZE,TARGET -n -l | 
              awk -v HOSTNAME=$HOSTNAME '"'"'/M/{print HOSTNAME ":" $2}'"'"' '
         done | 
    tee sorted.log

see: How to escape the single quote character in an ssh / remote bash command?

Luuk
  • 12,245
  • 5
  • 22
  • 33