6

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
    What happens when you do mkdir -p "$var" (which should be the correct syntax for POSIX shells or even better mkdir -p -- "$var", see http://unix.stackexchange.com/q/131766)? – Stéphane Chazelas Nov 06 '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. – Stéphane Chazelas Nov 06 '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. – Basile Starynkevitch Nov 06 '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. – Abel Cheung Nov 06 '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 06 '15 at 22:18

2 Answers2

8

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'
ZN13
  • 695
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.

woozymj
  • 24
  • 3
  • It is, I just wanted to provide more details. I have acknowledged ZN13's response in my answer now. – woozymj Nov 06 '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 Oct 25 '21 at 22:42
  • For example simple $* wont work the way you may think. In case >>>START>>>

    for i in $; do echo $i; done <<<END<<< Then this command: script.sh "a b" c "d e"
    will give you five lines instead of three. Each char in separate line. You'll need "$@" instead of $

    – Arpad Horvath Nov 16 '23 at 14:53