Home > Software design >  Get value from Read command and assign to a variable
Get value from Read command and assign to a variable

Time:01-07

I have a simple script that is something like the following:

#!/bin/bash
NUM=$(read -p "Number: ")
echo $NUM

When I run this from the command line i don't seem to get any value How can one take the results of read command that needs to be run within a script, save it to a variable, and then output that variable on the screen?

CodePudding user response:

If all else fails, try the documentation. From read --help:

Reads a single line from the standard input, or from file descriptor FD if the -u option is supplied. The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on, with any leftover words assigned to the last NAME. Only the characters found in $IFS are recognized as word delimiters. If no NAMEs are supplied, the line read is stored in the REPLY variable.

So:

read -p "Number: " NUM
echo $NUM

should do what you want. Alternatively

read -p "Number: "
echo $REPLY

would do the same thing, with little less typing.

  •  Tags:  
  • Related