2

I'd like to put a pause (maybe just sleep somehow?) in this one liner in between each restart because there's quite a few containers on this server and having it slow down the restarts will mean less of a load spike. If possible, I'd like to keep this a one liner, and avoid putting this into a bash shell script file. I know how to put a sleep into a for loop in a bash script, but I don't know how to put it into this. What's the $() part called?

docker restart $(docker ps --format "{{.Names}}" | grep -v somename)

So I'm just wanting to make a list of running containers, and restart each one with maybe a 30 second pause in between each restart.

Blake
  • 131
  • 3
  • 10
  • 1
    `$(...)` syntax is [command substitution](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_03), according to POSIX. – David Maze Oct 24 '18 at 01:23

1 Answers1

2

The meaning of $() as per here is:

The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command) is a modern synonym for command which stands for command substitution; it means, run command and put its output here.

What you need to perform all the restarts followed by a pause is a loop over the lines in the $(docker ps --format "{{.Names}}" | grep -v somename)" command, and inside the loop, do a docker restart $line and then a sleep 30 (for 30 seconds) command.

Something like this:

items=$(docker ps --format "{{.Names}}" | grep -v somename)
for word in $items
do
    docker restart $word
    sleep 30
done

Explanation:

items=$(docker ps --format "{{.Names}}" | grep -v somename)

This line sets a string variable named items that contains all the names of containers separated by spaces, as you did in your original command.

for word in $items

automatically splits the string by spaces, giving you a different container name in every iteration of the for loop.

Between

do

and

done

we have the code that is executed with each of the words in the items string, which is the following

    docker restart $word

We restart the docker container as you did, but only for one of the containers, its name read from $word.

    sleep 30

We sleep for 30 seconds before iterating again over the next $word value.


Single line version

If you want a compact version that you can run as a single line, you can do:

items=$(docker ps --format "{{.Names}}" | grep -v somename);for word in $items; do;  docker restart $word; sleep 30; done;
bonsvr
  • 2,262
  • 5
  • 22
  • 33
Kingmatusevich
  • 306
  • 1
  • 7