Operating System - HP-UX
1827882 Members
1140 Online
109969 Solutions
New Discussion

Question about variables in script

 
SOLVED
Go to solution
Artyom Voronchihin
Respected Contributor

Question about variables in script

Hello.
1. How can i check if variable exist or not in sh ? (I know how to do it in csh) E.G.
if [ $VAR not exist ]; then
VAR=$(expr $VAR + 1)
export VAR
else
VAR=0
export VAR
fi

2. What is the best syntax for arithmetic operations like VAR=$(expr $VAR + 1) in sh? I don't want to use expr command, i'd like something like VAR++ in C language.
"Intel inside" is not a label, it's a warning.
5 REPLIES 5
H.Merijn Brand (procura
Honored Contributor

Re: Question about variables in script

export VAR=`expr ${VAR:-0} + 1`

your logic is rather strange. If *not* defined increment, else set to 0

Enjoy, have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Stefan Farrelly
Honored Contributor
Solution

Re: Question about variables in script

1. To check if a variable exists;

[ -n "${:-}" ] && echo exists

replace for the variable name to check.

2. let =$+1


Im from Palmerston North, New Zealand, but somehow ended up in London...
Artyom Voronchihin
Respected Contributor

Re: Question about variables in script

Ooooops ! Mixed up sections. Correct would be
if [ $VAR not exist ]; then
VAR=0
export VAR
else
VAR=$(expr $VAR + 1)
export VAR
fi
"Intel inside" is not a label, it's a warning.
Steve Steel
Honored Contributor

Re: Question about variables in script

Hi


Use the -z option as shown in man test
for an existing variable.

if [ -z "$var" ]
then
echo not set
fi

See typeset -i in sh man

typeset -i x=1
x=$x+1


Steve Steel
If you want truly to understand something, try to change it. (Kurt Lewin)
Dietmar Konermann
Honored Contributor

Re: Question about variables in script

1)

if [[ -n ${VAR:-} ]]; then
((VAR+=1))
else
VAR=0
fi
export VAR

2)

((VAR+=1)) -or-
((VAR=VAR+1)) -or-
VAR=$((VAR+1))
...

Best regards...
Dietmar.
"Logic is the beginning of wisdom; not the end." -- Spock (Star Trek VI: The Undiscovered Country)