0

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?

1

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).
  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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