Shell string escape for command arguments

5,546

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"
Share:
5,546

Related videos on Youtube

beurg
Author by

beurg

Updated on September 18, 2022

Comments

  • beurg
    beurg over 1 year

    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?

  • beurg
    beurg over 9 years
    but mkdir "$ARGS" will result in a: mkdir '-p /tmp/pwet/foo bar'. I need the -p to be out of the string.
  • beurg
    beurg over 9 years
    Thanks, bash -c will do the job. Actually, due to integration, i can't use 2 variables, like explained in your first solution.
  • J doe
    J doe over 9 years
    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.