0

I have a simple bash script as follows:

#!/bin/bash

 n=$(( RANDOM % 100 ))

 if [[ n -eq 42 ]]; then
    echo "Something went wrong"
    >&2 echo "The error was using magic numbers"
    exit 1  fi

 echo "Everything went according to plan"

However, when I run the code by typing into the bash the following:

sh script.sh

I got the following output:

script.sh: 5: [[: not found 
Everything went according to plan

Why does it print script.sh: 5: [[: not found? I know I have missed something on line 2 but I do not know what.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
PharaohOfParis
  • 184
  • 2
  • 10
  • go to [ShellCheck](http://www.shellcheck.net/), cut-n-paste your code into the window, then review the suggestions on how to fix the script; once you've corrected your code, if you still have problems then come back and update/edit your question with your new code and whatever (new) error messages you're still receiving – markp-fuso Sep 21 '20 at 15:33
  • Avoid using `sh script.sh` to run scripts : if the shell behind `sh` is `bash` (and probably most others), it will execute in POSIX-compliant mode which it a bother to handle and isn't useful unless you need your script to behave correctly on different shells. Instead make your script executable (`chmod +x script.sh`) if it isn't already and execute it directly (`./script.sh`) which will use the shebang you've specified in the script to decide how to execute it – Aaron Sep 21 '20 at 15:40

1 Answers1

1

bash and sh are not the same shell, so the syntax is not the same even similar

for sh you want

if [ $n -eq 42 ]; then echo "Something went wrong" >&2 ;echo "The error was using magic numbers" ; exit 1 ;fi

so no double '[' ']' and '$' before 'n', and added missing ';'

Note also your code is wrong too for bash because of missing ';', you want :

if [[ n -eq 42 ]]; then echo "Something went wrong" >&2;echo "The error was using magic numbers" ; exit 1 ;fi
bruno
  • 32,421
  • 7
  • 25
  • 37