Skip to content
Advertisement

Quote a filename containing quotes and given as variable in Bash

Let’s say I have a directory path in variable DIR and I want to list this directory. If I care only about spaces in the path, then I could do

JavaScript

What should I write if I want to support also single and double quotes and other weird stuff in the directory path? Example:

JavaScript

Advertisement

Answer

Quotes are not just for spaces but for everything, so using the double quotes is the safety level you need here.

From Bash Reference Manual on Quoting:

3.1.2.3 Double Quotes

Enclosing characters in double quotes (‘”’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘’, and, when history expansion is enabled, ‘!’.


Let’s store this string into a file for later usage.

JavaScript

Read into a var:

JavaScript

Check its value:

JavaScript

Create a file with this value:

JavaScript

Check it has been created successfully:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement