Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I want to write a shell script, in which it will call different command according to the variable length. But I didn't figure it out yet.

My unwork script is here:

for i in n5 n25 
if ${#i} == 2;
then 
do 
    python two.py n5
elif ${#i} == 3;
do 
    python three.py n25
fi

How to evaluate the variable length in shell script?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

You probably want:

for i in n5 n25 
do
   if [ ${#i} -eq 2 ]; then 
       python two.py n5
   elif [ ${#i} -eq 3 ]; then
       python three.py n25
   fi
done

Note that:

  • for goes with do ... done.
  • if goes with then ... [elif; then] ... [else; then] ... fi.
  • the integer comparisons need -eq (equal) instead of = (for strings) and are written within brackets (if [ "$var" -eq 2 ], etc).
share|improve this answer
    
Can I nested another for loop inside such an if statement like above? The structure is like: for i in ... do .. if...then for j in... do ... done; fi done; –  Zen Jul 31 '14 at 3:13
1  
I tried, it worked. Amazing, thanks for your answer @fedorqui –  Zen Jul 31 '14 at 3:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.