Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

preserving a variable inside a while loop subshell 1

Status
Not open for further replies.

exsnafu

Technical User
Apr 25, 2008
99
0
0
US
I set the value of $port outside of a while loop

read in a file and pull two variable out of it, sometimes the second variable(port) is set, sometimes not.. but if not, then i want it to have a default value

seems to be the only way i can solve this is by explicitly checking for $port on each line and if its empty, set it inside the while loop.. any way to preserve the global value of $port in the loop?

Code:
#!/bin/bash
export port=161
export file=~/test1

while read server port; do
        echo "devcreate ${server%%.*} $server $port"
done < $file

contents of test1:
Code:
fqdn1.hostname.com
fqdn2.hostname.com
fqdn3.hostname.com 4161
fqdn4.hostname.com 161
fqdn5.hostname.com 4161
 


Try this:
Code:
#!/bin/bash
export dport=161
export file=~/test1

while read server port; 
do
  echo "devcreate ${server%%.*} $server ${port:-$dport}"
done < $file
[3eyes]

----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
aha, thanks.. i reversed the use but same difference.. this way i can keep $port as the global and have a new var just for the one offs inside the loop.

Code:
while read server nport; do
        echo "devcreate ${server%%.*} $server ${nport:-$port}"
done < $file



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top