Johan
Johan

Reputation: 40558

How to escape space in bash script from inline if?

I know that similar questions have been asked and answered before on stackoverflow (for example here and here) but so far I haven't been able to figure it out for my particular case.

I'm trying to create a script that adds the -v flag only if the variable something is equal to "true" (what I'm trying to do is to mount the current folder as a volume located at /src in the Docker container):

docker run --name image-name `if [ "${something}" == "true" ]; then echo "-v $PWD:/src"; fi` ....

The problem is that $PWD may contain spaces and if so my script won't work. I've also tried assigning "$PWD" to an intermediate variable but it still doesn't work:

temp="$PWD"
docker run --name image-name `if [ "${something}" == "true" ]; then echo "-v $temp:/src"; fi` ....

If I run:

docker run --name image-name -v "$PWD":/src ....

from plain bash (without using my script) then everything works.

Does anyone know how to solve this?

Upvotes: 1

Views: 340

Answers (2)

kojiro
kojiro

Reputation: 77137

Use an array.

docker_args=()
if something; then
    docker_args+=( -v "$PWD/src" )
fi
docker run --blah "${docker_args[@]}" …

Don't have arrays? Use set (in a function, so it doesn't affect outer scope).

Generally:

knacker() {
    if something; then
        set -- -v "$PWD:/src" "$@"
    fi
    crocker "$@"
}
knacker run --blah

But some commands (like docker, git, etc) need special treatment because of their two-part command structure.

slacker() {
    local cmd="$1"
    shift
    if something; then
        set -- -v "$PWD:/src" "$@"
    fi
    docker "$cmd" "$@"
}
slacker run --blah

Upvotes: 4

Alfe
Alfe

Reputation: 59516

Try this (using the array way):

declare -a cmd=()
cmd+=(docker run --name image-name)
if [ "${something}" = "true" ]
then
  cmd+=(-v "$PWD:/src")
fi
"${cmd[@]}"

Upvotes: 0

Related Questions