How to Keep Quotes When Passing Args to a Docker Command?

April 20, 2025 1 answer
Asked by balcony tomatoes
I'm working on a script that runs Docker commands for my containers without having to manually input the commands in the shell. Here's the basic script I've written: ```bash #!/bin/bash ALL_ARGS="$@" docker compose exec api ash -c "cd .. && alembic ${ALL_ARGS}" ``` However, I'm running into an issue: the variable `"$@"` does not preserve double quotes around the arguments, so when I try to run something like: ```bash ./alembic.sh revision --autogenerate -m "Message here" ``` It fails because it processes it as: ```bash alembic revision --autogenerate -m Message here ``` No quotes! Is there a way to keep the quotes intact when passing my arguments?

Answers

ash glazing~
First off, avoid using `ALL_ARGS="$@"`โ€”that just merges all arguments into one string. Instead, create an array to hold your arguments: ```bash args=( "$@" ) ``` Then, when calling commands, use: ```bash docker compose exec api ash -c 'cd .. && exec alembic "${args[@]}"' alembic-wrapper "${args[@]}" ``` You could simplify by using `-w dir` in the docker command to skip `cd`, like this: ```bash docker compose exec -w /some/dir api alembic "${args[@]}" ``` This keeps everything clean!

brief excursion: Tried your suggestion, but it didn't work out as expected. I entered: ```bash echo "docker compose exec -w /app/src api alembic $@" ``` The quotes still didn't appear in the command.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions