Shell scripting. Command substitution issue in my script
Here's what is going on. From the bash(1) man page, emphasis mine:
When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, ‘, or \. The first backquote 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.
So most likely you need more backslashes for the command substitution than a plain command.You can debug this by setting set -x
:
# someidformatted=`echo "${someid}" | sed 's/\//\\\//'`++ echo 314-12345/08++ sed 's/\//\\//'sed: 1: "s/\//\\//": bad flag in substitute command: '/'+ someidformatted=# someidformatted=$(echo "${someid}" | sed 's/\//\\\//')++ echo 314-12345/08++ sed 's/\//\\\//'+ someidformatted='314-12345\/08'
So, you can see that an occurrence of \\
gets turned to \
. Adding more backslashes works, but I prefer the $(command)
form:
# someidformatted=$(echo "${someid}" | sed 's/\//\\\//')