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

0
2
Asked By CuriousCoder42 On

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?

1 Answer

Answered By TechieTommy On

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!

ScriptSleuth93 -

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.