4

I try to get the value this command in a bash script returns but, It seem not to be returning anything

rr=$(read -p Enter -r)

echo "Is $rr"
read -p "java archive detected, Enter Y to download it again, N to continue $nl" -r
if [[ $REPLY =~ ^[Yy]$ ]] && [[ $(read -p Enter -r) == "Y" ]]; then

        echo "Y entered $REPLY"
        break;

    elif [[  $REPLY =~ ^[Nn]$  ]]; then

        echo "java Archive was extracted successfully to $java8Dir $nl"

    fi

3 Answers 3

4

That's because you are running the read in a command substitution ($()). There's no need for that. Just use:

read -p Enter -r rr
echo "Is $rr"

The var=$(command) syntax will set the value of var to whatever is returned by command. The read builtin doesn't return anything (apart from its exit status but that's not relevant here), so your variable remains empty. The syntax of read is read VAR and it will set the value of $VAR.

1

the proper syntax for read is

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

(from man bash)

  • first line sould be read -p Enter -r rr (you realy need to unescape backslash ? )
  • inner test should read

    if ... && [[ "$(read -p Enter R ; echo $R )" == "Y"  ]] ; tehn
    
1
  • Thanks, This worked for me, but what about test [[ "$(read -p 'Do you wish to install gtodo $nl' R) echo $R" =~ "Y" ]] && (sudo apt-get install gtodo) || (echo "gtodo not installed") Commented Oct 16, 2015 at 12:48
0

The command read -p Enter -r will place the value of what an user type inside the variable $REPLY (in Bash). So, this will work:

$ read -p Enter: -r
Enter:hello
$ echo "$REPLY"
hello

therefore, if you want the input of the user in var rr, do this:

$ read -p "Enter: " -r rr
Enter: hello
$ echo "$rr"
hello

Or, as one line:

$ read -p "Enter: " -r rr; echo "$rr"
Enter: hello
hello

All you need to do (in the script) to read the variable, and then print it, is:

read -p "Enter : " -r rr
echo "Is $rr"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .