asinkxcoswt asinkxcoswt - 1 year ago 53
Bash Question

How to make KSH function return only some echo message

Suppose I have a KSH function that return the sum of its arguments, but if the arguments are not supplied, it prompts for user inputs:

#!/bin/ksh
sum() {
typeset v1=$1
typeset v2=$2

test -z "$v1" && { printf "please enter v1: "; read v1; }
test -z "$v2" && { printf "please enter v2: "; read v2; }

echo $((v1+v2))
}


I would like to assign the result of this function to a variable, normally I would do it like this

typeset result=`sum 3 4`
echo $result # 7


But when I use the prompt version

typeset result=`sum`
echo $result


It has 2 undesired effect: first the prompt messages
please enter ...
do not display, second, the
result
will include the text
please enter ...
instead of just number.

$ typeset result=`sum`
$ 1
$ 2
$ echo $result
please enter v1: please enter v2: 3


How can I edit the function
sum
such that when no arguments supplied, it print the prompt messages
please enter ...
to stdout instead of returning it the the
result
variable?

Answer Source

First, I have to express that prompting for input in the middle of a function like this is a terrible idea. But if you're going to do it, you can either print the prompts to stderr or to /dev/tty

sum() {
  typeset v1=$1
  typeset v2=$2

  test -z "$v1" && { printf "please enter v1: " >&2; read v1; }
  test -z "$v2" && { printf "please enter v2: " > /dev/tty; read v2; }

  echo $((v1+v2))
}

Or, use read -p to have read print the prompt to stderr. (that is test -z "$v1" && read -p "Please enter v1: " v1)