Search code examples
bashwhitespacels

Problem using a variable with space passed into ls in a shell script


I'm trying to figure out how to handle a directory name with a space inside a shell script while passing it to ls. Below is a code sample - assuming that there is a directory called Hello world in the current directory, the first ls works, the second complains ls: Hello\ World: No such file or directory.

DST_DIR="Hello\ World"
ls Hello\ World
ls "${DST_DIR}"

Help. :(


Solution

  • Escape sequences aren't processed after expanding variables, so you shouldn't put the backslash in the string. It's only needed when you're typing an unquoted string literally.

    DST_DIR="Hello World"
    ls "${DST_DIR}"