Destiny Alabi
Destiny Alabi

Reputation: 81

how to Embed a function into read -p command

I want to know is it possible to place a function inside a read -p command.

flashRed="\033[5;31;40m"
red="\033[31;40m"
none="\033[0m"

question(){
  echo -e $none"Do you wan to remove"  $flashRed"$1?" $none
}
 read -p $question response

Upvotes: 0

Views: 33

Answers (2)

Destiny Alabi
Destiny Alabi

Reputation: 81

This worked when tried.

flashRed="\033[5;31;40m"
red="\033[31;40m"
none="\033[0m"

question(){
  echo -e $none"Do you wan to remove"  $flashRed"$1?" $none
}
 read -p "$(question $1) " response

Upvotes: 0

Socowi
Socowi

Reputation: 27360

I think a better formulation of your question would be

Is it possible to supply the output of a bash function as an argument for read -p.

The answer is yes. Use substitution $():

read -p "$(question argument) " response

Where argument is the string which will be accessed as $1 by your function. The argument can be a variable, for instance "$(question "$file") ".

But even if it was not possible, you could simulate what -p does. It just prints the given string without a newline.

echo -en "${none}Do you wan to remove ${flashRed}argument${none}? "
read response

-n disables the trailing newline of echo.

Or even better (because not all echo implementations support -e and -n):

printf "$none%s $flashRed%s$none? " "Do you wan to remove" "argument"
read response

Upvotes: 2

Related Questions