1

I just started learning bash/shell for fun, and I'm trying to create a simple script that should take user input, which should be the name of a pre-built array, and then say each item in that array with a pause in between.

Here's what I have so far:

#!/bin/sh
array=("foo" "bar" "baz")

read -p "Which array should I read to you? " answer

for item in ${answer[@]}
do
    say "$item [[slnc 1000]]"
done

Please let me know if you can point me in the right direction!

3
  • 1
    mywiki.wooledge.org/BashFAQ/006 Commented Apr 23, 2015 at 4:43
  • I tried it and it was working (mac env). with pause inclided Commented Apr 23, 2015 at 6:14
  • Did you save it as a file? What extension did you use? How did you run it? Any details will be helpful. Also, what happens if you add spaces into any of the array values - does it still work then? Commented Apr 23, 2015 at 6:37

1 Answer 1

1

You can access array using a variable array name like this:

#!/bin/bash

array=("foo" "bar" "baz")
read -p "Which array should I read to you? " answer

tmp="$answer"[@];

for item in "${!tmp}"; do
    echo "$item [[slnc 1000]]"
done

Then use above script as:

bash arr.sh
Which array should I read to you? array
foo [[slnc 1000]]
bar [[slnc 1000]]
baz [[slnc 1000]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much anubhava, I had a feeling there was a transitional step I was missing somewhere, and now I learned something new!

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.