Home > OS >  how to escape file path in bash script variable
how to escape file path in bash script variable

Time:10-14

I would like to escape a file path that is stored in a variable in a bash script. I read several threads about escaping back ticks or but it seems not working as it should:

I have this variable: The variables value is entered during the bash script execution as user parameter

CONFIG="/home/teams/blabla/blabla.yaml"

I would need to change this to: \/home\/teams\/blabla\/blabla.yaml

How can I do that with in the script via sed or so (not manually)?

CodePudding user response:

With GNU bash and its Parameter Expansion:

echo "${CONFIG//\//\\/}"

Output:

\/home\/teams\/blabla\/blabla.yaml

CodePudding user response:

echo "/home/teams/blabla/blabla.yaml" | sed 's/\//\\\//g'
\/home\/teams\/blabla\/blabla.yaml

explanation:

backslash is used to set the following letter/symbol as an regular expression or vice versa. double backslash is used when you need a backslash as letter.

CodePudding user response:

Using the solution from this question, in your case it will look like this:

CONFIG=$(echo "/home/teams/blabla/blabla.yaml" | sed -e 's/[]\/$*.^[]/\\&/g')

CodePudding user response:

Why does that need escaping? Is this an XY Problem?

If the issue is that you are trying to use that variable in a substitution regex, then the examples given should work, but you might benefit by removing some of the "leaning toothpick syndrom", which many tools can do just by using a different match delimiter. sed, for example:

$: sed "s,SOME_PLACEHOLDER_VALUE,$CONFIG," <<< SOME_PLACEHOLDER_VALUE
/home/teams/blabla/blabla.yaml

Be very careful about this, though. Commas are perfectly valid characters in a filename, as are almost anything but NULLs. Know your data.

  • Related