0

I would like to get an output based on the input we provided. For Example,

if I selected 1 it should take the 1st element in the array and the output should be My name is test

if I selected 2 it should take the 2nd element in the array and the output should be My name is test1

similarly, if I select all the output should be My name is test My name is test1 My name is test2 My name is test3

 a=("test" "test1" "test2" "test3")

testfunction() {
        echo My name is $a
}

echo "Enter a number"
select number in "test" "test1" "test2" "tes3" "all"; do
    case "$number" in
        test)
            testfunction "${a[0]}"; break;;
        test1)
            testfunction "${a[1]}"; break;;
        test2)
            testfunction "${a[2]}"; break;;
        test3)
            testfunction "${a[3]}"; break;;
        all)
            testfunction "${a[@]}"; break;;
    esac
done

Can someone please help me with this?

1
  • Why do you need a separate case for number in 1,2,3,4? Just verify that if $number is numeric and in the correct range, and then call testfunction "${a[$number]}". Commented Feb 19, 2020 at 8:22

2 Answers 2

1

As pointed out by other answers, you should use $1 in your testfunction(). Additionally, you can use a for loop to get your desired output when you select all as your input.

a=("test" "test1" "test2" "test3")

testfunction() {
        echo My name is $1
}

echo "Enter a number"
select number in "test" "test1" "test2" "test3" "all"; do
    case "$number" in
        test)
            testfunction "${a[0]}"; break;;
        test1)
            testfunction "${a[1]}"; break;;
        test2)
            testfunction "${a[2]}"; break;;
        test3)
            testfunction "${a[3]}"; break;;
        all)
            for i in "${a[@]}"; do testfunction "${i}"; done
            break;;
    esac
done
Sign up to request clarification or add additional context in comments.

Comments

0

You should be printing $1 instead of $a in your testfunction.

testfunction() {
        echo My name is $*
}

EDIT: Changing it to consider "all" case as well.

2 Comments

It is only taking the first element in the array even if I enter the all in the prompt.
My bad.... I didn't consider "all" case. Use $* instead of $1.

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.