passing arguments to docker exec from bash prompt and script

19,924

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()'.

Share:
19,924

Related videos on Youtube

curiousengineer
Author by

curiousengineer

Updated on January 05, 2020

Comments

  • curiousengineer
    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
    curiousengineer over 5 years
    how do i fix this?
  • Howard over 5 years
    Oops 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
    Noel Widmer about 5 years
    Can you explain why your solution works in order to raise the value of your contribution? Posting only code is often not very helpful.

Related