-1

I have following bash script code try to run a docker container through bash script but I am retreiving error.

#!/bin/bash
name=sudo docker ps | grep 'test' | awk '{print 
$1}'
sudo docker exec -it $name bash

error:

 docker exec requires at least two arguments
Cyrus
  • 84,225
  • 14
  • 89
  • 153
ash luck
  • 17
  • 5
  • first try `echo $name`. – Albin Paul Feb 13 '21 at 17:47
  • 2
    This might help: [How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/q/4651437/3776858) – Cyrus Feb 13 '21 at 17:50
  • @AlbinPaul, I tried its printing docker id but inside docker command it's not – ash luck Feb 13 '21 at 17:56
  • What do you get if you try `echo sudo docker exec -it $name bash` ? – Philippe Feb 13 '21 at 18:00
  • The syntax of your assignment to `name` is wrong -- it sets the variable `name` to the string "sudo" while running the command `docker ps... etc` (and doesn't capture its output). Check out the link Cyrus gave for how to do this correctly. – Gordon Davisson Feb 13 '21 at 20:48

1 Answers1

0

Assuming that you have a docker container actually called test running, the way the id is attained is incorrect. In order to expand a command into a variable, it needs to be contained within $() and so:

#!/bin/bash
name=$(docker ps | grep 'test' | awk '{print $1}')
sudo docker exec -it $name bash

A further note is the fact that you don't need sudo permissions to run docker ps ...

Additionally, you never need to pipe grep into awk as awk can do this for you:

name=$(docker ps | awk '/test/ {print $1}')

Further more, there is no need to pipe at all given the native capabilities built into docker-ps and so:

name=$(docker ps -q -f name=test)

This will print only the container id of a container named test. I'm assuming that the name is test here but it could be something else i.e. the label that is named test, in which case the filter would need to change:

 -f, --filter=[]
      Filter output based on these conditions:
      - exited=<int> an exit code of <int>
      - label=<key> or label=<key>=<value>
      - status=(created|restarting|running|paused|exited|dead)
      - name=<string> a container's name
      - id=<ID> a container's ID
      - before=(<container-name>|<container-id>)
      - since=(<container-name>|<container-id>)
      - ancestor=(<image-name>[:tag]|<image-id>|  â¨image@digestâ©)  -  conâ
   tainers created from an image or a descendant.
      - volume=(<volume-name>|<mount-point-destination>)
      -  network=(<network-name>|<network-id>)  -  containers connected to
   the provided network
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18