Bash adding whitespace when using mkdir with variable

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Bash adding whitespace when using mkdir with variable on this date .

I have observed that when I create a directory using a variable myvar=2099-100 mkdir $myvar && echo "done", bash adds a whitespace at the end of the directory name. The issue I have here is that this behavior seems to be very inconsistent.

If I run mkdir $myvar&& echo "done" the whitespace disappears.
If I run mkdir ${myvar} && echo "done" the whitespace disappears.

The inconsistency lies in the fact that if I create the directory without whitespace at the end once, then I can’t reproduce the issue. Running the same command that would create a directory with a whitespace does create it without it at the end.

So there are two questions:
What is the best practice when creating directories using bash. Should variable assignment contain quotes?
What is the correct way of referencing the variable when running mkdir (is it ${var} notation?)?
Why is bash adding whitespace when running mkdir $var && but not adding them when mkdir $var (I guess it has to do with expansion)?
Why after creating directory without a whitespace I can’t reproduce creation with a whitespace? Is the expanded variable cached somewhere?


The comments where right, the non breaking space was the issue. I may have forgotten to add that I’m running script on a remote server where I’m using heredoc to paste the script (unfortunately this is the workaround, terminal hijacking does not work). I’m copying the text from windows terminal (WSL) and we all know how windows clipboard works these days.

As for why I couldn’t reproduce the issue, once the file was modified in vim the correct space character was introduced, I’ve removed the space copied from the text file.

What I’ve learned here is to sanitize my input before pasting it to the terminal as that may cause a lot of not so obvious issues.

Leave a Reply

Your email address will not be published. Required fields are marked *