0

I just began with Shell script (#!/bin/bash) language. And here is a script:

for ((i=1;i<=200;i++)); do
if[$i>10] && [$i<50]; then   
    echo "Hello"; 
else   
    echo "Hi"; 
fi
done

It doesn't work, and I don't know why. Please help!

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
kabrice
  • 1,475
  • 6
  • 27
  • 51
  • http://shellcheck.net/ would identify your problem automatically without needing to involve any humans. – Charles Duffy Sep 01 '20 at 14:55
  • BTW, this code isn't compatible with `/bin/sh` at all. If it works for you, that means you're probably on an operating system where `/bin/sh` is provided by `bash`; but that means it'll break if you switch to an OS where `sh` is provided by ash, dash, posh, or another more-barebones interpreter. If you're going to use `for ((start; test; increment))` or other extended syntax, you need to use `#!/bin/bash`, not `#!/bin/sh`. – Charles Duffy Sep 01 '20 at 14:59
  • You're right. Just edited my code – kabrice Sep 01 '20 at 15:02

1 Answers1

1

I can certainly help with the syntax. Look at below corrected version and you'll figure out the things that you are missing.

#!/bin/sh

for (( i = 1; i <= 200; i++ ));
do
  if [[ $i -gt 10 ]] && [[ $i -lt 50 ]]; then
    echo "Hello";
  else
    echo "Hi";
  fi
done
Abhinav
  • 403
  • 4
  • 16
  • C-style `for` loops are not guaranteed to work with `#!/bin/sh`; neither is `[[ ]]`. Either switch to `#!/bin/bash`, or use `[ ]` and a legacy POSIX-compliant looping style. – Charles Duffy Sep 01 '20 at 14:55
  • And if you _are_ going to write bash-only code, `if (( i > 10 )) && (( i < 50 )); then` is arguably a lot easier to read than using `-gt` and `-lt`. – Charles Duffy Sep 01 '20 at 14:57
  • Beyond that, note the *Answer Well-Asked Questions* section of [How to Answer](https://stackoverflow.com/help/how-to-answer). This is both something that has been "asked and answered many times before", and caused by a typographic error. – Charles Duffy Sep 01 '20 at 14:57
  • I totally agree to your comments. My intention was to help a beginner with a working code so that he can get going. What is right and wrong, he can discover when he explores shell scripting in depth :) – Abhinav Sep 01 '20 at 15:10