1

Example 1.

Adding to the console works well

pic@pic:~/Desktop$ a="$(date +%s)"
pic@pic:~/Desktop$ b="$(date +%s)"
pic@pic:~/Desktop$ echo $[a+b]
2844184057
pic@pic:~/Desktop$

Example 2.

It's the same, but the script

pic@pic:~/Desktop$ cat a.sh 
#!bin/bash

a="$(date +%s)"
b="$(date +%s)"

echo $[a+b]pic@pic:~/Desktop$ sh a.sh 
$[a+b]
pic@pic:~/Desktop$ 

Why do I get a different result? How to get the same result?

EDIT:

pic@pic:~/Desktop$ ls -l $(command -v sh)
lrwxrwxrwx 1 root root 4 sty 10  2014 /bin/sh -> dash
pic@pic:~/Desktop$ ./a.sh
bash: ./a.sh: Brak dostępu
pic@pic:~/Desktop$ 

EDIT -1 :

It works like a run so

pic@pic:~/Desktop$ . ./a.sh
2844188704
pic@pic:~/Desktop$

EDIT -2 :

Does not work

pic@pic:~/Desktop$ chmod +x a.sh
pic@pic:~/Desktop$ ./a.sh
bash: ./a.sh: bin/bash: zły interpreter: Nie ma takiego pliku ani katalogu
pic@pic:~/Desktop$ 

EDIT -3 :

Corrected

pic@pic:~/Desktop$ cat a.sh 
#!/bin/bash

a="$(date +%s)"
b="$(date +%s)"

echo $[a+b]pic@pic:~/Desktop$ ./a.sh
2844189920
pic@pic:~/Desktop$ 
Anthon
  • 79,293
nowy1
  • 621
  • 2
  • 7
  • 15
  • 4
    You should run your script with ./a.sh not with sh a.sh. sh is (or at least could be) a different shell than bash and in your case apparently does not understand $[a+b] syntax. Check which shell sh is linked to with ls -l $(command -v sh). – jimmij Jan 24 '15 at 10:04
  • if a.sh is executable (x in ls -l) do ./a.sh if not do . ./a.sh – Archemar Jan 24 '15 at 10:10
  • 2
    FWIW, according to the bash man: "The format for arithmetic expansion is: $((expression)) The old format $[expression] is deprecated and will be removed in upcoming versions of bash." – PM 2Ring Jan 24 '15 at 10:14
  • 3
    Your shebang line reads #!bin/bash that should be #!/bin/bash. It is unlikely that you have bash in the subdirectory bin of the current directory. And because of that you are using sh (dash ?) on your system in the script – Anthon Jan 24 '15 at 10:18
  • Also see http://unix.stackexchange.com/questions/81599/why-should-i-use-expr-instead-of-expr and its links for more info on $((expression)) vs $[expression]. – PM 2Ring Jan 24 '15 at 10:22

1 Answers1

1

You script is missing the correct header, your shebang line reads

#!bin/bash

that should be

#!/bin/bash

It is unlikely that you have bash in the subdirectory bin of the current directory. And because of that you are using sh (dash ?) on your system in the script

Anthon
  • 79,293