linuxbashmacoscommand-line

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

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?>

Solution

  • 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")