1

I'm writing a basic script to practice working with arrays. When I run the script I get errors but when I run the same command in the terminal it executes.

#!/bin/bash

declare -a StringArray

StringArray=("blue" "green")

for val in ${StringArray[@]}; do echo $val done

I've given the script executable permission. What am I missing?

enter image description here

Mint
  • 113
  • 3
    If you have made the script executable then just run it with ./script.sh. sh script.sh executes the script with the sh shell not the bash shell. They are two different command interpreters. – codlord Mar 13 '22 at 15:21

1 Answers1

4

With the command sh script.sh, you try to run the script with sh. sh is symlinked to dash. dash is the standard command interpreter of Ubuntu. It is a different shell than bash, essentially with more minimal features, but very fast. Bash is much better for interactive use, so remains the default interpreter for the interactive prompt. Here is an excellent answer on the difference between these command interpreters.

Instead, run your script with

bash script.sh

to have it executed under the proper shell.

If you place your script in a directory in your PATH and make it executable, you can run it at the command prompt merely by typing script.sh. At that moment, the shebang line, #!/bin/bash tells the system that bash should be used. When running the script as bash script.sh or sh script.sh, that shebang line is just a comment and not interpreted at all.

vanadium
  • 88,010