4

I'm trying to create a directory which has space in name e.g. "user test" when I fire mkdir -p "user test" it works for me.

When I put "user test" in variable mkdir fails, it creates "user and test" separately

var="user test"
mkdir -p $var 

I also tried mkdir -p "$var"

Can someone please suggest where I'm doing wrong ?

5
  • 5
    What happens when you do mkdir -p "$var" (which should be the correct syntax for POSIX shells or even better mkdir -p -- "$var", see unix.stackexchange.com/q/131766)? Nov 6 '15 at 12:32
  • 2
    What's the shell? In rc, it should be var='user test'; mkdir -p -- $var as double quotes are not special in that shell and there's no implicit split+glob on unquoted variables like there is in Bourne-like shells. Nov 6 '15 at 12:35
  • Don't create directory with spaces in their name. Use an underscore mkdir user_test. It will be much easier after. Nov 6 '15 at 12:47
  • 2
    As a side note, I find certain attitude in answer and comment worrisome. Such "wisdom" exists because of sloppy scripts and programs written during earlier days. Instead of solving the artificial restriction, such attitude encourages the sloppy behavior to persist and spread. In the long run, one would need more time to troubleshoot why something doesn't work, or even causing trouble for others. Nov 6 '15 at 14:26
  • On what system and with which shell have you tried this? The normal mkdir -p $var should create 2 directories user and test, while mkdir -p "$var" should create only 1 dir user test.
    – ott--
    Nov 6 '15 at 22:18
5

You have to escape the space

mkdir hello\ there

You can also encapsulate the string, this way you do not have to escape the space.

mkdir 'hello there'
0

Answer by ZN13 is correct. Just to provide more details -

You can do this by using an escape sequence (per-character escaping) such as a backslash ().

Example

mkdir Good\ Morning

Here, the backslash helps in escaping the space character before 'Morning'.

It is never recommended to use space in filenames, directories in Linux, because it makes data copying and other tasks associated with using filenames/directory names difficult.

2
  • It is, I just wanted to provide more details. I have acknowledged ZN13's response in my answer now.
    – woozymj
    Nov 6 '15 at 20:46
  • Would you be specific at "It is never recommended to use space"? Is this due to the difficulty in search?
    – Cloud Cho
    yesterday

Not the answer you're looking for? Browse other questions tagged or ask your own question.