1

I have a very basic shell script containing

#!/bin/sh
NAME[0]="Hello"
echo ${NAME[0]}

So when I run this script an error occurs stating

./test.sh: 2: ./test.sh: NAME[0]=Hello: not found
./test.sh: 3: ./test.sh: Bad substitution

So basically I looked through a few tutorials and found this to be the basic way to declare arrays. So I am confused as to why this is an error. Any ideas?

2
  • 1
    You're running /bin/sh, If that shell is in fact bash, calling it by that name puts it in POSIX compatibility mode, where there are no arrays. Use shebang of #!/usr/bin/env bash instead. Commented Apr 22, 2016 at 20:06
  • @ghoti IMHO answer already contained this info :) Commented Apr 22, 2016 at 20:24

1 Answer 1

3

You are starting your script as #!/bin/sh, which has a soft link to dash (The current version of sh which conforms with the POSIX 1003.2 and 1003.2a specifications for the shell) and dash doesn't support arrays. In debian 8 onwards dash has become default shell, so if you run ls -la /bin/sh the output will be /bin/sh -> dash

However bash still remains the default login shell, only the default /bin/sh used in shell scripts has been changed. So if you run your code on terminal, it will work just fine. More information on why this switch was made in Ubuntu can be found here.

If you want to use arrays in your script then you must start your script with #!/bin/bash

So your script works perfectly if modified like this

#!/bin/bash
NAME[0]="Hello"
echo ${NAME[0]}

More information on Dash as Sh DashAsBinSh

Sign up to request clarification or add additional context in comments.

2 Comments

It worked, thanks! Can i also consider bash as the default shell since I didnt install it? It was already there when I installed the os.
@Patrick bash remains the default login shell, only the default /bin/sh used in shell scripts has been changed, more information can be found here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.