Wednesday, May 22, 2019

Read-command in bash script




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=($(, but I ran my script through Shellcheck last week, and it said I should use 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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...