0

I've a script that ssh's onto other vms and runs a command.
Working code is as follows:

  declare -a envname=("hostname1" "hostname2")
    # Looping through array
    for i in "${envname[@]}"
    do
       # loging on to environments, running a df command
       ssh "$i" "df -h" 
    done

This works perfectly, but the code will get messy as more hostnames are added to the list. As such, I want a .txt file to replace the array. The textfile looks like this:

hostname1
hostname2
hostname3

Here's my attempt with a .txt file:

sed '/^[ \t\r\n]*$/d' hosts.txt | while read hosts; 
     do
         echo "$hosts"  
         ssh "$hosts" "df -h" 

done

The "echo$hosts" prints each hostname which looks fine, but I receive the error on the next line of code:

"name or service not knownname "hostname"" 

I assume this is some sort of whitespace/linespace issue as the hostnames look fine in the previous command. The sed '/^[ \t\r\n]*$/d line was my attempt to remove whitespace, but this isn't working.

Yunter
  • 274
  • 3
  • 17
  • 1
    Use `set -x` (or `bash -x yourscript`) to debug, never `echo` (which is unreliable [by specification](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html); see the APPLICATION USAGE and RATIONALE sections). Presumably your file has DOS newlines; a `set -x` log (for bash -- some `/bin/sh` implementations don't quote as well) will show them as `$'\r'` sequences. – Charles Duffy Nov 02 '18 at 16:01
  • 1
    ...btw, when you fix that, you'll hit a different issue: [ssh breaks out of while loop in bash](https://stackoverflow.com/questions/9393038/ssh-breaks-out-of-while-loop-in-bash); short form: either switch to a FD other than stdin, or put ` – Charles Duffy Nov 02 '18 at 16:02
  • Also, note that piping into a `while read` loop puts that loop in a subshell so you can't set variables there; see [BashFAQ #24](http://mywiki.wooledge.org/BashFAQ/024) for a more detailed explanation and fix. – Charles Duffy Nov 02 '18 at 16:04
  • ...you can also log the value in your variable in way that's guaranteed to generate visible characters with `printf 'hosts=%q\n' "$hosts"` – Charles Duffy Nov 02 '18 at 16:05
  • Your hosts.txt file has DOS line endings; notice the odd error message. – chepner Nov 02 '18 at 16:06
  • Thanks for this info. It was due to DOS line endings. Thanks for linking that "ssh breaks out of while loop". Much appreciated everyone – Yunter Nov 02 '18 at 16:11

0 Answers0