kelp99
kelp99

Reputation: 69

How do you get user input and then call a function with that user input in its name?

How do I write a bash script that asks the user for a number (1, 2 or 3) which is used to call a function with that number in its name? After that, the function then displays a message with the function number within it.

Here's what I have so far:

#!/bin/bash

read -p "Enter a Number (1,2, or 3): " num

function foo() {
   echo This message is from function $1
}

foo $num

This is just a generic function that returns whatever the user inputs. I just don't know how to incorporate what the user inputs into the function name. Like if the user inputs 1, foo1 is called. If user inputs 2, foo2 is called. 3, foo3 is called etc. Is there a better way to do this other than using if else statements and writing three separate functions?

Any help is appreciated!

Upvotes: 0

Views: 1103

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74605

Sure, there's no reason why you can't call a function whose name is a combination of a string literal and a variable:

#!/bin/bash

foo1() { echo 'hello from foo1!'; }
foo2() { echo 'hello from foo2!'; }
foo3() { echo 'hello from foo3!'; }

read -p "Enter a Number (1,2, or 3): " num

if [[ $num = [123] ]]; then # validate input
  foo"$num"
fi

Upvotes: 3

Evan Jaramillo
Evan Jaramillo

Reputation: 1

Maybe something like this:

#!/bin/bash

echo Enter Number:
read num

function1() { echo one; }
function2() { echo two; }

case $num in
    1)
        function$num
    ;; 
    2)
        function$num
    ;;
esac

Upvotes: 0

Related Questions