1

I want use an array in my shell script test.sh as follows:

#!/bin/bash
index=100345
NAME[0]="Zara"
NAME[$index]="Qadir"
echo "First Index:" ${NAME[0]}
echo "Second Index:" ${NAME[$index]}

but when execute it by sh test.sh:

NAME[0]=Zara: not found
NAME[100345]=Qadir: not found
test.sh: ${NAME[...}: Bad substitution

How to solve it?

3
  • 3
    Only bash (bourne again shell) and ksh (korn shell) support array. If you are trying to run your script using the legacy sh (bourne shell), it will not work as it doesn't support array. Commented Jun 29, 2015 at 6:54
  • 1
    echo $SHELL to see what shell you are using. Commented Jun 29, 2015 at 7:26
  • @Will: $SHELL shows the login shell, not necessarily the shell you are using. Commented Jun 29, 2015 at 10:30

2 Answers 2

3

Don't do this:

sh test.sh

That runs the script under whatever is the default shell.

Instead, do this:

bash test.sh

This assures that it is bash which runs the script.

Example

Using your test.sh script, this generates errors:

$ sh test.sh
test.sh: 3: test.sh: NAME[0]=Zara: not found
test.sh: 4: test.sh: NAME[100345]=Qadir: not found
test.sh: 5: test.sh: Bad substitution

This does not:

$ bash test.sh
First Index: Zara
Second Index: Qadir

On my system, sh is a link to dash which is a fast POSIX shell but it does not support arrays. To get fancy features like arrays, one must use a fancy shell like bash.

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

Comments

0

The array is not supported by the simple terminal. Use the command bash your_Script_Name.sh. EX: I have a script file array.sh in which I am using the array. In this case, i will run this script as:

bash array.sh

1 Comment

Welcome to Stack Overflow. It looks like your answer has all the same content as the existing answer. Instead of repeating content, consider upvoting an existing answer if you found it helpful. If you have something substantial to add to the post, then you may post a new answer.

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.