Skip to content

Instantly share code, notes, and snippets.

@andras-tim
Forked from szz/doci
Last active June 4, 2020 08:24
Show Gist options
  • Save andras-tim/2c3b05ebe3c6c8950d02b50efb351ec6 to your computer and use it in GitHub Desktop.
Save andras-tim/2c3b05ebe3c6c8950d02b50efb351ec6 to your computer and use it in GitHub Desktop.
get the prefered interactive shell in a given docker conatiner
#!/bin/bash
set -eufo pipefail
SHELL_PREFERENCE=(
'bash'
'zsh'
'sh'
)
function main()
{
local container_id="${1:-}"
if [ -z "${container_id}" ]; then
error 255 \
'No container name supplied'
fi
if ! is_container_exist "${container_id}"; then
error 254 \
"'${container_id}' is not valid container" \
"$(list_containers)"
fi
for shell_cmd in "${SHELL_PREFERENCE[@]}"
do
if is_command_available_in_container "${container_id}" "${shell_cmd}"; then
set -x
exec docker exec -it "${container_id}" "${shell_cmd}"
fi
done
error 253 \
'There is no supported shell in the container'
}
function error()
{
local exit_code="$1"; shift
local messages=("$@")
printf '%s\n' "${messages[@]}" >&2
exit "${exit_code}"
}
function is_container_exist()
{
local container_id="$1"
list_containers \
| grep -qw "$1"
}
function list_containers()
{
docker container ls --format 'table {{.Names}}\t{{.ID}}'
}
function is_command_available_in_container()
{
local container_id="$1"
local command="$2"
docker exec -t "${container_id}" which "$(printf '%q' "${command}")" \
>/dev/null
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment