-1

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?

T. Ujasiri
  • 317
  • 1
  • 3
  • 14
  • 1
    `exec` stops your shell from running. – Charles Duffy Sep 09 '21 at 16:19
  • 1
    BTW, note that all-caps variables are in reserved space. Using lowercase names for variables you define yourself will stop you from accidentally overwriting things that are meaningful to the shell. – Charles Duffy Sep 09 '21 at 16:20
  • See [BashFAQ #1](http://mywiki.wooledge.org/BashFAQ/001) re: best practices for iterating over a file line-by-line in bash. Using it, this would look more like `while IFS= read -r line; do printf '%s\n' '' "EXECUTING ==> nslookup $line"; nslookup "$line"; done <./rhel_hosts` – Charles Duffy Sep 09 '21 at 16:22
  • 2
    Why do you need to put the command into a variable in the first place? – Barmar Sep 09 '21 at 16:25

1 Answers1

2

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612