How can detect container ID immediately after container start?

For example If my container looks as busybox pwd

  sudo docker run -it --name busybox.$(date +%Y-%m-%d-%H.%M.%S) busybox pwd & sudo docker inspect busybox.$(date +%Y-%m-%d-%H.%M.%S)

I can see result

 [23] 1530
 [
     {
         "Id": "4a520dec6b6efc1df770eed652f0f898c340ac734bd778b6a9be8f4cbd8c3a18",
....
[23]+  Stopped                 sudo docker run -it --name busybox.$(date +%Y-%m-%d-%H.%M.%S) busybox pwd

However If I start container as busybox /bin/sh
I see full result

  [24] 1736
  []
  Error: No such object: busybox.2022-09-04-10.28.29
  [24]+  Stopped                 sudo docker run -it --name busybox.$(date +%Y-%m-%d-%H.%M.%S) busybox /bin/sh

But container is present in

  sudo docker ps

I need to see container ID in the same terminal session for both type of container (daemon and interactive) - is it possible? Or I need to open another terminal session and monitoring result of

  sudo docker ps

I cans ee multiple potential problems:

  • You should not use $(date +%Y-%m-%d-%H.%M.%S) multiple times, because the time between the two execution can change, so you will refer to a wrong container name.Save the result to a variable, and use the variable multiple times.
  • I am not sure if yoiu really wanted to do this: pwd & sudo docker ...
    If you want to run your container in the background, you can just use the --detach or -d flag, but then you need to run a command in the container which keeps that container alive. pwd will not do that. Even if you try to send the container to the background, pwd will show you the output and stop so the container will stop immediately. If your command worked, I guess it ran so fast that the time did not change. Then you tried running a shell, which keeps the container alive when you use an interactive terminal (-it), so you can se a container running, but the time could change and this is not the same container you try to inspect.

If you run the container in the background, you will get the ID on the standard output:

cid=$(docker run -d --name test httpd:2.4)
Unable to find image 'httpd:2.4' locally
2.4: Pulling from library/httpd
5b1423465504: Already exists
ceb4a75630f5: Already exists
f20566210577: Already exists
ee03e037f8b6: Already exists
8220bbf1aee7: Already exists
Digest: sha256:70999c4a17c796dd28f86f9c847b30f28abaed6ef1fd72a44282b1c941238804
Status: Downloaded newer image for httpd:2.4
echo $cid
f7cf77ce4d3e36a4cbe1856156516c2146c1f97c0aea6fa27b999af0a5679f6b

Or you can use a cidfile:

docker run --rm -it --cidfile test.cid bash 

From an other terminal:

cat test.cid
ac2bb9d28ba546c659cbcc6103714f775404aa2d3d0e070ddef5e7efbdad53ef