How to store a path with white spaces into a variable in bash

后端 未结 2 1038
星月不相逢
星月不相逢 2021-01-20 15:55

I want to store /c/users/me/dir name into a variable to pass it to cd system call.

Works when typing:

$ cd \'/c/users/me/dir

2条回答
  •  清酒与你
    2021-01-20 16:51

    Double-quote your path variable with spaces, to preserve it,

    dirName="/c/users/me/dir name"
    cd "$dirName"
    

    Actually, dirname is a shell built-in, recommend using an alternate name to avoid confusion with the actual command.

    From the man bash page,

    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, ‘!’.

提交回复
热议问题