0

I am running into an issue where I am comparing two files (alert.txt and env.txt) and based on common value, I am pulling complete line data from env.txt based on matching entry. I am reading these values into while loop and then invoking a function as follows. the ssh call is not working and also the while loop inside start_admin not working

#!/bin/bash
start_admin()
{
ssh -n -f $user@$host "sh -c 'cd $domain; ./script.sh > /dev/null 2>&1'"
while !(netstat -na | grep -E $host:$port|grep -E LISTEN) 2>/dev/null
sleep 30
do
echo "waiting"
done
echo "started"
}

grep -Ff alert.txt env.txt | (while IFS=" " read -r r1 r2 r3 r4 r5
do
user=$r2
host=$r3
domain=$r4
port=$r5
done
start_admin $user $host $domain $port
)

and contents of alert.txt is:
env2
env3

and that of env.txt is :
env1 user1 host1 /app/domain1/ port1
env2 user2 host2 /app/domain2/ port2
env3 user3 host3 /app/domain3/ port3

I could solve this with multiple if else loops, but that is not a desired solution, please guide me in right direction as to what is missing ?

0

1 Answer 1

1
  1. Use join instead of grep here to avoid false positives
  2. Because your while read loop completes before you run start_admin, you only launch it once (done should be AFTER start_admin)
  3. In start_admin, don't use $user, $host and so on, use $1, $2 (or use them but don't pass them as parameters when calling the function)

I'm not sure exactly what you try to achieve, but here is a revised version already.

#!/bin/bash
start_admin()
{
  sanitized_domain=${domain//'"'/'\"'}
  ssh -n -f "$user@$host" "sh -c 'cd \"$sanitized_domain\"; ./script.sh >/dev/null 2>&1'"
  while ! netstat -na | grep -q " $host:$port .*LISTEN"; do
    echo waiting
    sleep 30
  done
  echo started
}

join alert.txt env.txt | while IFS=' ' read -r env user host domain port; do
  start_admin
done
)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @Camusensei, I got the direction and with the above revised solution, I am able to do the desired task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.