2

I want to construct a function that will change its user input prompt based on its parameter.

my_fucntion takes 1 parameter as db_host after prompting the user for input:

function provide_host () {
    echo "Enter NAME OR IP OF ${function_param1} DATBASE HOST: "
    read global function_param1_db_host
}

So if I call the function as

function provide_host (primary)

it should prompt as

echo "Enter NAME OR IP OF PRIMARY DATBASE HOST: "

but if I use

function provide_host (secondary)

it prompts

 "Enter NAME OR IP OF SECONDARY DATBASE HOST: "

My idea is that I have to use an if statement for that, but I'm not sure if I can use the function's parameter as a variable for promptin the user inside the function.

1 Answer 1

6

You can use $1 to get the first parameter:

function provide_host () {
    echo "Enter NAME OR IP OF $1 DATBASE HOST: "
    read global function_param1_db_host
}

or to convert it to upper case:

function provide_host () {
    echo "Enter NAME OR IP OF ${1^^} DATBASE HOST: "
    read global function_param1_db_host
}

Then call your function with:

provide_host primary
provide_host secondary

However, I'd do it slightly differently. Instead of trying to set a global variable, I'd prompt in stderr and return the IP from the function in stdout:

function provide_host() {
    read -p "Enter NAME OR IP OF ${1^^} DATABASE HOST: " host >&2
    printf "%s" "$host"
}

primary_db_host=$(provide_host primary)
secondary_db_host=$(provide_host secondary)
9
  • Redirecting the prompt to standard error is a bit of an over-kill. The read utility already displays the prompt on standard error by default.
    – Kusalananda
    Commented May 31, 2022 at 11:54
  • @ilkkachu The 5.1 manual, in documenting read -p, explicitly says that the prompt is displayed on standard error. Note that the manual you linked to was last updated in 2020. Besides, the shell will always prompt the user on the standard error stream. select does this too, for example.
    – Kusalananda
    Commented May 31, 2022 at 12:12
  • @ilkkachu read has prompted the user on the standard error stream since 1996 when it first got the -p option. And again, the shell will always prompt the user on standard error. This is common knowledge, or should be.
    – Kusalananda
    Commented May 31, 2022 at 12:48
  • @ilkkachu The question is tagged with bash. The shell in question is bash.
    – Kusalananda
    Commented May 31, 2022 at 13:03
  • @ilkkachu Bash is the only shell relevant for this question though (see tags). Its read utility prompts on standard error, and has always done so. This is easily tested, and is documented in the manual.
    – Kusalananda
    Commented May 31, 2022 at 13:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .