0

I have a file called "s1" and it contains the following:

#!/bin/bash
var1=5
var2=4
if (( var1 > var2 ))
 then 
  echo "$var1 more than $var2"
fi

On executing the file I get the following:

s1: 4: var1: not found

In most cases, such an error occurs due to incorrect declaration of variables, for example:

var1 = 5

but I'm declaring the variable without any extra spaces.
While executing this script, I noticed that I have created two files with the names 4 and var2 respectively Why am I getting such an error?

mzlvv4k
  • 5
  • 2
  • Your script works as expected on my linux. No idea what you have done! You simply set exec bits and call it? – Klaus Apr 29 '22 at 18:57
  • Yes. I execute the file with `sh s1` command. By the way, when I write the script in a line in the terminal it works: `var1=5; var2=4; if (( var1 > var2 )); then echo "$var1 > $var2"; fi` – mzlvv4k Apr 29 '22 at 19:00
  • Why you answer with "yes"? You did something totally different! You run a bash script with `sh` shell which simply can't work. So you should simply set exec bit and execute the file itself instead of calling a shell manually. We should close the question as the problem has nothing to do with the code shown or the text provided in the question. Please vote to close! – Klaus Apr 29 '22 at 19:06
  • Thank you all for your help. Now I run the script with `./s1` command and it works. – mzlvv4k Apr 29 '22 at 19:08

1 Answers1

1

You're running the script with sh, not bash. For example you might be doing sh s1. You should be doing ./s1 so that the system will use the shebang (#!/bin/bash) to determine which interpreter to run the script with.

I'm not sure how sh interprets double-parens (( )), but it's certainly not the same as Bash, so it's trying to run a command called var1 and redirect the output to a file called var2.

As for why you have a file called 4, you probably tried adding a dollar sign $ at some point.

wjandrea
  • 28,235
  • 9
  • 60
  • 81