2

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

ls "$DIR"

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

DIR="/Users/Mick O'Neil (the \"Terminator\")/Desktop"
echo $DIR # prints /Users/Mick O'Neil (the "Terminator")/Desktop
ls <what should I write here?>
Aivar
  • 6,814
  • 5
  • 46
  • 78
  • [How to escape single quotes within single quoted strings?](https://stackoverflow.com/q/1250079/608639), [When to wrap quotes around a shell variable?](https://stackoverflow.com/q/10067266/608639), [When is double-quoting necessary?](https://unix.stackexchange.com/q/68694/56041), [How to handle spaces in filenames using double quotes in a Bash script](https://stackoverflow.com/q/32767951/608639), [Listing files in date order with spaces in filenames](https://stackoverflow.com/q/4583801/608639), etc. – jww Aug 29 '18 at 12:46

1 Answers1

5

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.

$ cat file
Mick O'Neil (the "Terminator")

Read into a var:

$ filename=$(<file)

Check its value:

$ echo "$filename"
Mick O'Neil (the "Terminator")

Create a file with this value:

$ touch "$filename"

Check it has been created successfully:

$ lt "$filename"
-rw-r--r-- 1 me me 0 Mar  1 15:09 Mick O'Neil (the "Terminator")
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598