I'm trying to start using read -r, but no luck so far.
The following script (added below) should make a list of SSH servers from /etc/hosts, and then execute the command. I use it for simple administration things, adding users, etc.
I normally use sshservers=($(
read -r
in stead.
So I added that, but now my script gets stuck when I run it.
Is someone able to help me out how I should properly use read -r
in stead?
(And if you have any further tips or notes, please let me know, I'm still learning Bash, as you might see by looking at my script hehe).
Thanks in advance!
#!/bin/bash
serverlist=/home/demo/serverlist.txt
: > "$serverlist"
sed -e '/^#/d' /etc/hosts | awk '{print $2}' >> "$serverlist"
sed -i -- '/^localhost/ d' "$serverlist"
#sshservers=($( sshservers=$(read serverlist)
for sshserver in "${sshservers[@]}"
do
ssh -t demo@"$sshserver" "hostname && sudo ls /root/"
done
echo "done"
EDIT: /home/demo/serverlist.txt contains IP's with the following format, not sure if it helps:
192.168.1.1
192.168.1.2
192.168.1.3
Answer
With older versions of bash (if you want the lines in an array):
sshservers=()
while read -r servername; do
sshservers+=("$servername")
done < "$serverlist"
In bash 4+
you can use readarray
:
sshservers=()
readarray sshservers < "$serverlist"
Or in this case if you don't really need the servernames in a file, you could just loop over the results for the commands like so:
while read -r sshserver: do
ssh -t "demo@$sshserver" "hostname && sudo ls /root/"
done < <(sed -e '/^#/d' /etc/hosts | awk '{print $2}' | grep -vE '^$|^localhost')
No comments:
Post a Comment