Frank-Rene Schäfer
Frank-Rene Schäfer

Reputation: 3352

How to excape special syntax characters in string variable in bash

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?

Upvotes: 0

Views: 33

Answers (1)

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10133

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

path="/this/path/contains whitespace/and/asterisk */myfile.txt"
printf '%q\n' "$path"

Upvotes: 1

Related Questions