Yifan Zhang
Yifan Zhang

Reputation: 1501

How come using ./shell.sh get error but . shell.sh works

a shell script:

VAR=(aa bb cc)

for i in "${VAR[@]}"
do
        echo $i;
done

when run it using . ar_test.sh, it works.

zhangyf@zhangyf-desktop:~/test$ . ar_test.sh 
aa
bb
cc

but fails in this way,

zhangyf@zhangyf-desktop:~/test$ ./ar_test.sh 
./ar_test.sh: 9: Syntax error: "(" unexpected

There are other lines in the file, so line 9 is actually VAR=(aa bb cc). I know the difference is that the latter forks a new shell process while the former ones run the script in the current shell, but why does the result differs so much?

Upvotes: 1

Views: 148

Answers (2)

knittl
knittl

Reputation: 265221

Your current shell is likely to be bash. If your shebang-line starts /bin/sh, then VAR=(aa bb cc) will not work. Using source (the . command), the script will run in your current shell (that is,bash`).

Make sure the first line of your script is:

#!/bin/bash

Another way to start the script in a new shell is bash ar_test.sh.

In response to the heated discussion in the comments: If you want to keep your script portable on systems where bash might not be installed in its standard location, you should put #!/usr/bin/env bash as first line instead.

Upvotes: 2

Ineu
Ineu

Reputation: 1373

The difference is not a fork, but different shells. . sources file in the current shell and ./ar_test.sh runs executable with default shell (/bin/sh), which may not support arrays. Use shebang as the first line of your script to specify proper shell:

#!/bin/bash
...other code goes here...

Upvotes: 8

Related Questions