My bash script gets filenames with spaces and other odd characters.
How do I print these filenames back out to the terminal with the escapes in the right places so the user can just copy-and-repaste the filename so that it can be reused as a parameter to the same or another script?
I wrote a test script which reads as follows:
#! /bin/bash
echo ""
echo "testing the insertion of '\' in filenames having spaces"
echo "the parameter you gave was: '$1'"
echo "when printed directly the filename looks like: '$1'"
echo "when printed with echo \$(printf '%q' $x) it looks like: " $(printf '%q' $1)
Running the script went as follows:
bash test.sh this\ filename\ has\ spaces
testing the insertion of '\' in filenames having spaces
the parameter you gave was: 'this filename has spaces'
when printed directly the filename looks like: 'this filename has spaces'
when printed with echo $(printf '%q' ) it looks like: thisfilenamehasspaces
What I want to see the script produce is:
when printed directly the filename looks like: 'this\ filename\ has\ spaces'
Seems simple but the question is hard to form for Google. All help appreciated. Thanks.
This:
means this:
which, since
printf '%q'concatenates its arguments, means this:What you want is this:
which tells
printf '%q'thatthis filename has spacesis all one argument, so it will quote the spaces inside.I’d also recommend putting the command-substitution inside double-quotes:
which happens not to be necessary in this case, but will be necessary if the filename ever has a character that causes
printf '%q'to use$'...'-style quoting instead of backslashes.