0

GIVEN:

A string variable containing characters that are used by bash for expansion or as delimiters, e.g.

> path="/this/path/contains whitespace/and/asterisk */myfile.txt"

GOAL:

I want to expand the variable in a way that those bash syntax elements are backslashed (or disabled but not simply quoted), i.e. the output of solution would be

> solution $path
/this/path/contains\ whitespace/and/asterisk\ \*/myfile.txt

QUESTION:

Isn't there a command in bash that does that, rather than having to struggle with all special characters on my own?

1 Answer 1

1

Use the %q specifier of printf (a bash builtin):

path="/this/path/contains whitespace/and/asterisk */myfile.txt"
printf '%q\n' "$path"
Sign up to request clarification or add additional context in comments.

2 Comments

Recent (5.0+?) versions also support escaped=${original@Q}
You have to be careful with, e.g. ${original@Q} which may simply single-quote the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.