Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

LINK TO THIS FORUM!

Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Partner With Us!

"Best Of Breed" Forums Add Stickiness To Your Site
Partner Button
(Download This Button Today!)

Feedback

"...I've learned more from your forums in 3 days than 3 months at school and on the job combined..."

Geography

Where in the world do Tek-Tips members come from?

preserving a variable inside a while loop subshellHelpful Member! 

exsnafu (TechnicalUser)
10 Aug 10 13:14
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
 
Helpful Member!  LKBrwnDBA (MIS)
10 Aug 10 14:07


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
 

exsnafu (TechnicalUser)
10 Aug 10 14:37
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



 

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close