Bash no parameters for $ (function parameters)
source link: https://www.codesd.com/item/bash-no-parameters-for-function-parameters.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Bash no parameters for $ (function parameters)
I want to create a script that use basic (prompt and confirm) functions multiple times, when I try to set the return to any variable the function ignore the parameters
function promp() {
echo $*
read response
echo $response
}
function confirm() {
echo $*
read -rp $'(y/N) : ' -ei $'N' key;
case "$key" in
[yY][eE][sS]|[yY])
echo true
;;
*)
echo false
;;
esac
}
IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE
Expected:
SOME QUESTION
(y/N) : N
WRITE SOMETHING
#<< "some text"
false
some text
Obtained:
(y/N) : N
#<< "some text"
SOME QUESTION false
WRITE SOMETHING some text
I know the problem is the echo within the function is part of the variable data, but I want to get this printed.
How can I do this or which is the best way to do this
Your functions are called in context of command substitution:
STRING_RESPONSE=$(promp "WRITE SOMETHING")
So the standard output of the promp "WRITE SOMETHING"
command is attached to the context of the variable assignment.
However, the standard error is still attached to the terminal. If you redirect the output of echo
to the file descriptor 2
, then the output will be displayed to the user just when the echo
is called, e.g.:
function promp() {
echo >&2 "$*"
read response
echo "$response"
}
Another way is to use -p
option: read -p "Your prompt: "
which prints the prompt string to the standard error as well.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK