passing arguments to docker exec from bash prompt and script
Solution 1
docker exec -it d886e775dfad sh -c "mongo --eval 'rs.isMaster()'"
This calls the shell (sh
) executing the script in quotation marks.
Note that this also fixes things like wildcards (*) which otherwise do not work properly with docker exec.
Solution 2
You need to run (there's a missing single quote in your example):
cmd="mongo --eval 'rs.isMaster()'"
Followed by (without the quotes around $cmd
):
docker -H $node2 exec d886e775dfad $cmd
By including quotes around $cmd
you were looking for the executable file mongo --eval 'rs.isMaster()'
rather than the executable mongo
with args mongo
, --eval
, and 'rs.isMaster()'
.
Related videos on Youtube

curiousengineer
Updated on January 05, 2020Comments
-
curiousengineer almost 3 years
I am trying to execute a command inside my mongodb docker container. From my linux command prompt it is pretty easy and works when I do this
docker exec -it d886e775dfad mongo --eval 'rs.isMaster()'
The above tells me to go to a container and execute the command
"mongo --eval 'rs.isMaster()' - This tells mongo to take rs.isMaster() as an input and execute it. This works and gives me the output.
Since I am trying to automate this via bash script, I did this
cmd="mongo --eval 'rs.isMaster()"
And then tried executing like this
docker -H $node2 exec d886e775dfad "$cmd"
But I guess somehow docker thinks that now the binary file inside the container is not mongo or sth else and it gives me the following error:
rpc error: code = 2 desc = oci runtime error: exec failed: container_linux.go:247: starting container process caused "exec: \"mongo --eval 'rs.isMaster()'\": executable file not found in $PATH"
-
curiousengineer over 5 yearshow do i fix this?
-
Howard over 5 yearsOops sorry forgot the solution. Try omitting the quotes around the variable. Then it should expand the variable inline and turn into
docker -H $node2 exec d886e775dfad mongo --eval 'rs.isMaster()'
-
Noel Widmer about 5 yearsCan you explain why your solution works in order to raise the value of your contribution? Posting only code is often not very helpful.