-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutable_dshell
More file actions
73 lines (60 loc) · 1.69 KB
/
executable_dshell
File metadata and controls
73 lines (60 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env bash
set -euo pipefail
CONTAINER=""
USER="root"
LOGIN=0
usage() {
cat << EOF
Usage: dshell CONTAINER [OPTIONS]
Open an interactive shell in a Docker container easily.
Arguments:
CONTAINER Docker container name
Options:
-h, --help Display this help message
-l, --login Use login shell (default: false)
-u, --user USER User to run the shell as (default: root)
Examples:
dshell c1
dshell c1 --user myuser
dshell c1 --login --user myuser
EOF
}
generate_shell_command() {
local user=$1
local container=$2
local login_flag=""
if [[ "${LOGIN}" -eq 1 ]]; then
if login_path=$(docker exec "${container}" which login 2>/dev/null); then
echo "docker exec -ti -u root ${container} ${login_path} -f ${user}"
return
fi
login_flag="-l"
fi
if bash_path=$(docker exec "${container}" which bash 2>/dev/null); then
echo "docker exec -ti -u ${user} ${container} ${bash_path} ${login_flag}"
else
echo "docker exec -ti -u ${user} ${container} sh ${login_flag}"
fi
}
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
usage ; exit 0 ;;
-l|--login)
LOGIN=1 ; shift ;;
-u|--user)
USER="$2"; shift 2 ;;
-*)
echo -e "Error: Unknown option: $1\n"; usage ; exit 1 ;;
*)
if [[ -n "$CONTAINER" ]]; then
echo -e "Error: Too many arguments\n"; usage ; exit 1
fi
CONTAINER="$1"; shift ;;
esac
done
if [[ -z "${CONTAINER}" ]]; then
echo -e "Error: CONTAINER argument is required\n"; usage; exit 1
fi
echo -e "Opening shell in container '${CONTAINER}' as user '${USER}'\n"
exec $(generate_shell_command "${USER}" "${CONTAINER}")