# # Why does this variable become blank?
APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed

Why does this variable become blank?

I've removed advertising from most of this site and will eventually clean up the few pages where it remains.

While not terribly expensive to maintain, this does cost me something. If I don't get enough donations to cover that expense, I will be shutting the site down in early 2020.

If you found something useful today, please consider a small donation.



Some material is very old and may be incorrect today

© July 2015 Anthony Lawrence

Anonymous asks:

Why does this variable become blank? It's obviously set in the first part, but it goes away.


who am i | if grep tony > /dev/null  2>&1
 then
 echo "Setting source directory to /usr1/src"
 export src_path=/usr1/src
 echo $src_path
 else
 src_path=/usr2/src
fi
echo -e "src_path= $src_path"
 

What happens here is actually very simple, although it may seem baffling at first. Yes, the "if then" block sets the variable to either /usr1/src or /usr2/src, so it surprised you to find it blank in the last line which echoed "src_path= $src_path".

What you missed is that piping "who am i" to that "if" block caused the creation of a new shell for everything in the block. Variables changed in a new shell don't change the values in the calling shell, so $src_path was still blank.

Something like this will work much better:

IAM=`who am i | cut -d" " -f1`

if [ $IAM == "tony" ]
 then
 ..
 

brinan White noted that the script will work in ksh


If you found something useful today, please consider a small donation.



Got something to add? Send me email.





(OLDER)    <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

->
-> Why does this variable become blank?


Inexpensive and informative Apple related e-books:

iOS 10: A Take Control Crash Course

Take Control of IOS 11

Take Control of High Sierra

Take control of Apple TV, Second Edition

Take Control of Pages





More Articles by © Anthony Lawrence





Printer Friendly Version

Have you tried Searching this site?

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us


Printer Friendly Version





We are stuck with technology when what we really want is just stuff that works. (Douglas Adams)




Linux posts

Troubleshooting posts


This post tagged:

Bash

Forum

Scripting

Shell



Unix/Linux Consultants

Skills Tests

Unix/Linux Book Reviews

My Unix/Linux Troubleshooting Book

This site runs on Linode