Re: David - Re: Bash file to variable string problem -- must be simple. What am I missing?
- Date: Mon, 4 Mar 2019 09:33:33 -0500
- From: Greg Wooledge <wooledg@xxxxxxxxxxx>
- Subject: Re: David - Re: Bash file to variable string problem -- must be simple. What am I missing?
On Mon, Mar 04, 2019 at 08:59:37AM -0500, deb wrote:
> Interestingly -- two people got to different, correct, answers quickly,
> without seeing the actual string (that you mentioned a couple of times).
Experience. Those who have been using the Unix command line long enough
know where the dangers are, and how to avoid them, and how to trigger
them in someone else's imperfect code.
Seeing something like
echo $fname | ...
immediately raises red flags. For some of us, more than one red flag.
The big flag is for the unquoted variable expansion. We know that this
can break if there are leading spaces, or trailing spaces, or multiple
back-to-back spaces, or some glob character like a * with spaces around
it, in the filename. The vast majority of the time, if it's going to
break, it'll be because of incorrect quoting.
The smaller red flag is for echo. This can break if the filename is,
or contains, something with special meaning to echo. For example, if
the filename is -n then you're just totally screwed. But also, if the
filename contains certain backslash+letter sequences, some versions of
echo will interpret those -- and some versions WON'T. You can't even
guarantee the results. This is FAR less likely to be a problem, but it's
still something to keep in mind.
For this particular question ("I want the filename without its extension"),
the right answers have already been given, so I won't rehash that.
If in the future there were actually some need to write the filename to
a pipe, this is the only safe way to do it:
printf %s "$fname" | ...
That doesn't add a newline (which echo does). So if you also need to
add a newline to it, then:
printf %s\\n "$fname" | ...
There's some flexibility in the quoting for the first argument.
Some people will write '%s\n' and some will write "%s\n" or "%s\\n" --
these are acceptable alternatives.
The important thing is that you do NOT write printf "$fname" because
that's wrong. If you write that, then you're back to the original
problem where some part of the filename may be interpreted by the command
you're using to write it, which is not what you want.