I'm trying to create "/tmp/pwet/foo bar" with this:

DIR="/tmp/pwet/foo bar"
ARGS="-p ${DIR}"
mkdir $ARGS

For integration reasons, I have to keep the ARGS building in 2 steps: ARG = some_options + $DIR This code create 2 dirs: /tmp/pwet/foo and ./bar. this is not what I want.

I've tried a lot of escaping things, without results. I run the script with bash. What's the good solution?


1 Answer 1


The problem is not with the contents of the variable (and this is why you can try with as many escape characters as you want), but with the fact that bash replaces $ARGS with the variable contents literally, so the space within it will be an actual space in the command.

Just use mkdir "$ARGS" instead (i.e., enclose the variable reference in "s)

UPDATE: As discussed in the comments, in order to have the -p and other options as not being part of the directory name, define 2 variables instead:

OPTS="-p -whatever" and ARGS="/tmp/pwet/foo bar"

then later issue mkdir like this:

mkdir $OPTS "$ARGS"

Alternativelly, if you want full control over this using escape characters plus the possibility of having multiple directories, some with spaces, some without, options, all mixed together you can put the entire command in a variable and execute it with bash -c.

Check the example below as a starting point you can play with:

MKDIRCMD="mkdir -p \"A B\" \"C D\""
echo $MKDIRCMD # Notice the \ characters are NOT part of the string
bash -c "$MKDIRCMD"
  • but mkdir "$ARGS" will result in a: mkdir '-p /tmp/pwet/foo bar'. I need the -p to be out of the string.
    – beurg
    Nov 5, 2014 at 10:43
  • in this case I'd recommend you to use 2 separate variables, one for the options one for the directory(ies). Something like OPTS="-p -x -whatever" and ARGS="tmp/pwet/foo bar". Then use mkdir $OPTS "$ARGS". Otherwise, there would be no way the shell to guess what spaces you intend to use as separators what you intend as part of an argument.
    – Marcelo
    Nov 5, 2014 at 10:46
  • Thanks, bash -c will do the job. Actually, due to integration, i can't use 2 variables, like explained in your first solution.
    – beurg
    Nov 5, 2014 at 11:23
  • You are welcome. Noticed you are new to StackExchange. If you think this answer is what you were looking for, please accept it so that others know this is closed as well as provides reputation credits to the person who provided the answer.
    – Marcelo
    Nov 5, 2014 at 11:34

Not the answer you're looking for? Browse other questions tagged .