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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I assign a value in if statement to global variable???

Status
Not open for further replies.

suhaimi

Technical User
Aug 3, 2001
71
US
Hi,
How do I assign a value in if statement to global variable???

Real case:
sh> if [ "`echo "TEST TOAST"|awk '{myvar=$1}'`" ]
> then
> echo $myvar
> fi
TEST
This method does not work!!!!! Do you have any idea how to make this possible?
I know the other way is to do this is:
sh>myvar=`echo "TEST TOAST"|awk '{myvar=$1}'`

but is it possible to assign a variable in if statement to global variable either using awk/nawk or other unix command????

Please help, Thanks
Suhaimi


 
Use

myvar=`echo "TEST TOAST"|awk '{print $1}'`

Hope this helps.

CaKiwi
 
Dear CaKiwi,
Thanks for the effort but the only thing is it'll not work in if condition. I need a workable method that could assign a value within if statement condition to a global variable.

Thanks,
Suhaimi
 
shell_Stuffer=$(echo $var | awk ' {
if ($0 == "anticipated return") {
print 0
else
print 1
}
}')

if [ "$shell_Stuffer" -gt 0 ]
then
"Improper value."
else
:
fi
 
Hi Marsd,
The method you use does not solve the problem. The assignment of variable is outside the if condition portion. It is the same as :
myvar=`echo "TEST TOAST"|awk '{print $1}'`
if [ "$myvar" == "TEST" ]
then
:
fi

Sorry for the hassle
Suhaimi
 
I don't know how you are getting your variable but
it doesn't matter, I didn't read your post well.
Are you are trying to test the first
element of a whitespace separated string?

awk -v will takes the variable input from the global
environment
str="test toast"

parse_first_element_ws() {
var=$1
awk -v c=$var ' BEGIN {
if (c) {
split(c,arr, " ")
print arr[1]
} else {
print "1" #SIMULATED ERROR
}'
return
}

Hope this was it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top