Command line function for querying and returning input

I am trying to write a helper function for use in a bash script to take the prompt string of a variable and return the value the user enters. What I'm sitting and waiting for the user to enter a value without displaying a hint at first, which is perplexing. It also stores the echo in the return value ($ foo) and does not store the value read from the pid variable.

!#/bin/bash
pid=0
promptValue() {
  msg="$1"
  echo -e "$msg"
  read val
  pid=$val
}

foo=$(promptValue "type something")

EDIT: For those who may want to use this in the future for their own use, this is a complete (functional) script that is designed to send email (in this case to my mobile phone) to tell me when the process is taking a long time to complete. I'm sure there should be a better way to do this, but to me. :-) (I wrote them so that they are used in the bash function library elsewhere.)

#!/bin/bash

promptValue() {
 read -p "$1"": " val
 echo $val
}

alertme() {
 if [ -z "$email" ]; then
   email=$(promptValue "Enter email")
 fi

 if [ -z "$email" ]; then 
   echo "ERROR: No email set!"
   exit 1
 fi

 if [ -z "$pid" ]; then
   pid=$(promptValue "Enter pid")
 fi

 if [ -z "$pid" ]; then 
   echo "ERROR: No pid set!"
   exit 1
 fi

 ps -ef | grep $pid | grep -v grep > /dev/null 2>&1
 while [ $? eq 0 ]; do
  sleep 10
  ps -ef | grep $pid | grep -v grep > /dev/null 2>&1
 done

 echo "Process Complete" | mailx -s "Process Complete" $email
}

alertme

Thanks again everyone!

+3
source share
3 answers

, , , , return n, n 0-255. , , echo. - , stderr, read -p.

$ demo() {
    local num
    echo "capture this"
    echo "Message to user" >&2
    read -p $1 num
    echo $(( num * 2 ))
    return 42
}
$ result=$(demo "Enter a number: ")
Message to user
Enter a number: 12
$ echo $?
42
$ echo "$result"
capture this
24
$ echo "$num"
[null][newline]
+3

- :

#!/bin/bash
pid=0
promptValue() {
  read -p "$1"": " val
  pid=$val
}

promptValue "type something"
echo 'pid:'$pid'!'

$(...), " ", "command" ( echo ..).

+2

, , , foo. val, noit :

promptValue "type something"
foo=$pid
0

Source: https://habr.com/ru/post/1727049/


All Articles