linuxbashfor-loopnslookup

nslookup command in loop, only executes once in Linux Bash script


In the following script block, I attempt to execute an nslookup on each fqdn being read from a file. However, the script stops after executing the first nslookup command. Code:

for HOST in `cat ./rhel_hosts`
do
       echo;
       echo "EXECUTING ==> nslookup ${HOST}"
       CMD="nslookup ${HOST}"       
       exec $CMD
done

Any idea why there is no subsequent execution of the nslookup command?


Solution

  • Replace

    exec $CMD
    

    with just

    $CMD
    

    The exec command replaces the shell process with the program that you execute, instead of running it in a child process. The loop ends because the shell script is no longer being executed in the process.