Reputation: 1
I am writing a shell script that parses a logfile. The important part is this:
rx=$(echo "$logfile" | grep -o "rx_value.*" | grep -o "[0-9]\{1,10\}")
echo rx=$rx
The following is printed to STDOUT (WRONG):
rx=
If i remove the double qoutes from $logfile like this:
rx=$(echo $logfile | grep -o "rx_value.*" | grep -o "[0-9]\{1,10\}")
echo rx=$rx
The following is printed to STDOUT (CORRECT):
rx=0
I was pretty sure that it was a good thing to use double quotes around variables, so I have used them on all variables in my script. The information I have found so far, says that if one do NOT put double quotes around variables, the result could become wrong because of word splitting, globbing etc.
Can anyone explain what is happening here?
Edit:
$logfile contains the logfile downloaded with wget:
$logfile=(wget -q -O -"http://www.example.com")
Upvotes: 0
Views: 798
Reputation: 11232
I think your logfile
has a newline between rx_value
and the number you are looking for. The echo
command with an unquoted parameter expansion will convert the newline to a space. See word splitting or field splitting in the documentation.
Upvotes: 1
Reputation: 38718
You didn't mention the value of $logfile
. Your information is correct -- the difference between no quotes and double quotes is precisely field splitting and globbing. So if you rely on one of them to happen, you will get wrong results with double quotes.
UPDATE. Okay, so your variable containt a log file retrieved with wget
. May I suggest using a pipe instead?
rx=$(wget -q -O -"http://www.example.com" |
grep -o "rx_value.*" |
grep -o "[0-9]\{1,10\}")
But this will probably output the same that your double-quoted example, and I would trust this more than what you think is correct answer.
Upvotes: 0
Reputation: 360095
What happens if you quote the variable on output?
echo "rx=$rx"
Not doing this is often the source of "mysterious" behavior.
Upvotes: 0