[olug] sed issues inside of a script
Christopher Cashell
topher-olug at zyp.org
Tue Nov 13 08:25:22 UTC 2007
On Nov 13, 2007 12:53 AM, John Hobbs <john at velvetcache.org> wrote:
> My problem lies with (I believe) sed. I'm trying to escape a path
> with sed and store that in a variable and it isn't working with `` but
> it is with $().
Close, it's not a sed issue, but a bash issue.
> Here's my debugging demo script:
[Snip: script.]
"When the old-style backquoted form of substitution is used, backslash
retains its literal meaning except when followed by "$", "`", or "\".
The first backticks not preceded by a backslash terminates the command
substitution. When using the "$(COMMAND)" form, all characters between
the parentheses make up the command; none are treated specially."
> The output to that is:
>
> $ ./example.sh
> /home/jmhobbs/Desktop
> \/home\/jmhobbs\/Desktop
> sed: -e expression #1, char 9: unknown option to `s'
>
> \/home\/jmhobbs\/Desktop
> $
In the broken example, sed is being passed in 's/\//\\//g', instead of
's/\//\\\//g' (note the missing backslash in the latter part).
> Just curious if anyone knows why that would happen. Am I missing
> something, I thought `` and $() were equivalent.
They're almost equivalent, but not quite 100%. Also, using backticks
is deprecated, so best practice would be to use $() in any new scripts
that you write.
Also, if you're having trouble with shell scripts, one of the most
useful things you can do to debug is run it with -x. Doing that
causes bash to echo the commands as they're run, along with the
results and evaluations.
For example, for this snip of your script:
THEPATH='/home/jmhobbs/Desktop'
# Won't work
ESCAPEDPATH=`echo $THEPATH | sed 's/\//\\\//g'`
echo $ESCAPEDPATH
# Will work
ESCAPEDPATH=$( echo $THEPATH | sed 's/\//\\\//g' )
echo $ESCAPEDPATH
When run with bash -x, you get the following:
topher at nexus:/tmp$ bash -x temp.sh
+ THEPATH=/home/jmhobbs/Desktop
++ echo /home/jmhobbs/Desktop
++ sed 's/\//\\//g'
sed: -e expression #1, char 9: unknown option to `s'
+ ESCAPEDPATH=
+ echo
++ echo /home/jmhobbs/Desktop
++ sed 's/\//\\\//g'
+ ESCAPEDPATH='\/home\/jmhobbs\/Desktop'
+ echo '\/home\/jmhobbs\/Desktop'
\/home\/jmhobbs\/Desktop
Here you can see the values of each expression, including the first
sed that is one backslash short of what it should be.
Hope this helps, and good luck. ;-)
> - John Hobbs
--
Christopher
More information about the OLUG
mailing list