[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Functions and interactive scripts
From: |
Pierre Gaston |
Subject: |
Re: [Help-bash] Functions and interactive scripts |
Date: |
Thu, 19 Mar 2015 12:30:55 +0200 |
On Thu, Mar 19, 2015 at 12:20 PM, Richard Taubo <address@hidden> wrote:
> Hi!
>
> I was think about creating an interactive script and output the result
> to a variable like this:
> =========================
> function ask_question() {
> printf "$1"
> read ANSWER
> printf "Answer: $ANSWER\n"
> }
>
> the_answer=$(ask_question "Are you happy?")
> printf "$the_answer"
> =========================
>
> This obviously does not work.
> Do I need to use a global variable in such a case, or are there better
> options?
> With global:
> =========================
> function ask_question() {
> printf "$1"
> read ANSWER
> }
>
> ask_question "Are you happy?"
> the_answer=$ANSWER
> ANSWER=""
> printf "Answer: $the_answer\n"
> =========================
>
>
> Thanks for input!
>
> Richard Taubo
>
the most straightforward is to use read -p as it prints the prompt on
standard error
function ask_question() {
read -p "$1" ans
printf "Answer: %s\n" "$ans"
}
Using a global variable is not a bad idea either, as it avoids the subshell
and is faster.