13

I'm wanting to detect in "docker run" whether -ti has been passed to the entrypoint script.

docker run --help for -t -i

-i, --interactive=false     Keep STDIN open even if not attached
-t, --tty=false             Allocate a pseudo-TTY

I have tried the following but even when tested locally (not inside docker) it didn't work and printed out "Not interactive" always.

#!/bin/bash

[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'
hookenz
  • 36,432
  • 45
  • 177
  • 286
  • 1
    If you just have it echo `$-` what do you get? Also, what version of bash are you running? – Eric Renouf Jul 08 '15 at 00:45
  • Oddy enough, that should work. I think -t would do. – hookenz Jul 08 '15 at 01:20
  • 1
    A script run as a script (`/path/to/script` or `bash /path/to/script`) isn't run in interactive mode. Run that command at your shell prompt or source it (`. /path/to/script`) and it will work the way you expect. – Etan Reisner Jul 08 '15 at 01:24
  • Thanks. Nevermind. I found out I can detect tty with the test -t option. I can't tell if -i was specifid but -t will at least tell me if there is a tty and if that fails I can instruct to rerun with -ti – hookenz Jul 08 '15 at 02:18
  • Not sure why the downvote, but I have clarified it's the entrypoint script I'm wanting to detect this in. – hookenz Jul 08 '15 at 02:19

1 Answers1

9

entrypoint.sh:

#!/bin/bash

set -e

if [ -t 0 ] ; then
    echo "(interactive shell)"
else
    echo "(not interactive shell)"
fi
/bin/bash -c "$@"

Dockerfile:

FROM debian:7.8

COPY entrypoint.sh /usr/bin/entrypoint.sh
RUN chmod 755 /usr/bin/entrypoint.sh
ENTRYPOINT ["/usr/bin/entrypoint.sh"]
CMD ["/bin/bash"]

build the image:

$ docker build -t is_interactive .

run the image interactively:

$ docker run -ti --rm is_interactive "/bin/bash"
(interactive shell)
root@dd7dd9bf3f4e:/$ echo something
something
root@dd7dd9bf3f4e:/$ echo $HOME
/root
root@dd7dd9bf3f4e:/$ exit
exit

run the image not interactively:

$ docker run --rm is_interactive "echo \$HOME"
(not interactive shell)
/root
$

This stackoverflow answer helped me find [ -t 0 ].

Community
  • 1
  • 1
Ewa
  • 553
  • 7
  • 13
  • 8
    From my testing this will tell you whether the `-t` option has been passed, but tell you nothing about whether `-i` was passed. – javabrett May 21 '16 at 08:15
  • You also need the `[ -t 1 ]` to detect interactive mode. The `--tty` option in docker run just tells docker to allocate a tty, but doesn't mean you get a shell. So for completeness, you need something like `[[ -t 0 && -t 1 ]]` to ensure that even if the image is run with a tty, but the `--detach` option is passed, you can still detect that this is a non-interactive session, and do something appropriate – smac89 Apr 20 '21 at 21:11