Search code examples
bashshellline

shell script to read one line and process line by line


I have below file with fqdn of server & user of that server in same line. cat servers.txt

server1 user1 \n
server2 user2 \n
server3 user3 \n

I am writing a shell script where I can use one server at a time to do ssh and perform some commands there and move to next server in line. For example, ssh to server1 and sudo to user1 and do the stuff, than move to server2. So I written below and tried to tweak but no workaround found. Its not working. Please help.

ROOT_PATH=/home
SERVERS_FILE=servers.txt

while IFS= read -r line; do
        server=`cut -d' ' -f1 $line`
        user=`cut -d' ' -f2 $line`
        echo $server ::: $user
        echo "grep -rw lookeupword $ROOT_PATH/$user" | ssh $server "sudo -iu $user bash"
done <<< "$SERVERS_FILE"

Solution

  • This will work.

    #!/usr/bin/env bash
    ROOT_PATH=/home
    SERVERS_FILE=servers.txt
    
    while IFS= read -r line; do
            server=$(echo -n ${line} | awk '{print $1}')
            user=$(echo -n ${line} | awk '{print $2}')
            echo $server ::: $user
            #echo "grep -rw lookeupword $ROOT_PATH/$user" | ssh $server "sudo -iu $user bash"
    done < "$SERVERS_FILE"