Because the page
variable can contain arbitrary text, you shouldn't use echo
, you should use printf
.
times="$(printf %s\\n "$page" | wc -l)"
Also note that if you have more than one trailing newline in the output of your grep
command, you won't get the expected result no matter what, because command substitution strips trailing newlines and the echo
command or the printf
command I use alike will add in exactly one trailing newline, regardless of how many were stripped from the grep
output when the $page
variable was being set.
Of course, even in this case the $times
variable will contain a bunch of extra spaces at the start, because that's how wc -l
will output its information. So this answer doesn't address the broader issue with your script: It looks like you are pressing bash
into service where awk
would serve better.
I could be wrong about that, depending on what you intend to do with the $times
variable, but I seriously doubt it. Most likely you can do what you need (all of what you need) with an awk
one-liner.
$(…)
) should be quoted (e.g.,times="$(printf "%s\n" "$page" | wc -l)"
), unless there is a good reason not to. This is one of those special cases: sincewc
is fairly well behaved (except for its annoying habit of writing leading spaces), I recommend usingtimes=$(printf "%s\n" "$page" | wc -l)
(or, for example,num_lines=$(wc -l < "filename")
) to get the shell to strip the spaces. – G-Man Says 'Reinstate Monica' Apr 07 '16 at 23:04export
are sometimes different); the shell won't word split the RHS regardless of quoting. So you'd still have the extra spaces. You could avoid the issue by leaving$times
unquoted when it is used later, however. – Wildcard Apr 07 '16 at 23:12whois=\
whois 100.43.81.149`; bool="$(printf %s\n "$whois" | grep -q netname:)" ; if $bool;then:fi` bool variable is always true although in this case it is not. Would you help please? – NecNecco Apr 11 '16 at 15:00if
takes a command, not a variable.) – Wildcard Apr 11 '16 at 15:23