Issue
Was trying to do a quick-and-dirty curl call like so:
curl -u username:$(read -s -p "password: ") https://some.basic.auth.url.com
However, this fails every time. What's more, I attempted to see what's happening with something like:
echo you entered: $(read -p "enter some text: ")
However, the output is simply:
you entered:
I'm clearly missing something essential about the use of this command (or Bash in general). Can someone shed some light on:
- Can this sort of thing even work? why?
- If so, how could I change this to make it work without going to a script file?
Solution
echo "You entered: $(IFS= read -rp "Enter some text: "; printf '%s' "$REPLY")"
From help read
:
read ... [name ...]
Reads a single line from the standard input ... 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 secondNAME
, and so on, with any leftover words assigned to the lastNAME
. Only the characters found in$IFS
are recognized as word delimiters.If no
NAMEs
are supplied, the line read is stored in theREPLY
variable.
IFS= ...
: Don't trim leading and trailing spaces-r
: Don't mangle backslashesecho "$REPLY"
: If you don't supply anyNAME
, the line read is stored in the$REPLY
variable. However,read
doesn't print it so the command substitution expands to nothing. Consequently, you have to print it explicitly with, for example,printf
Note that if you use read
inside $(...)
, the variable is lost as soon as you leave the substitution. Better approach:
IFS= read -rp "Enter some text: " var
echo "You entered: $var"
Answered By - PesaThe Answer Checked By - Pedro (WPSolving Volunteer)