Last active
December 18, 2018 12:33
-
-
Save klausmeyer/c699828e178ffa6817ccd44f3f32dcda to your computer and use it in GitHub Desktop.
Docker Tools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
function message() { | |
>&2 echo "$1" | |
} | |
function find_container() { | |
local tokens=($@) | |
local output=$(docker ps | grep ${tokens[0]}) | |
for token in "${tokens[@]:1}"; | |
do | |
output=$(echo "$output" | grep $token) | |
done | |
lines=$(echo "$output" | wc -l) | |
if [ "$lines" != "1" ]; then message "Found more than one possible containers for passed arguments"; return 1; fi | |
local cid=$(echo "$output" | head -n1 | cut -d' ' -f1) | |
if [ -z "$cid" ]; then message "Could not find the container for the passed arguments."; return 1; fi | |
message "Found matching container with ID $cid" | |
echo $cid | |
} | |
function docker_exec() { | |
local cid="$1" | |
local cmd="$2" | |
docker exec -it -e COLUMNS=$(tput cols) -e LINES=$(tput lines) $cid $cmd | |
} | |
function main() { | |
if [[ $# < 2 ]]; then message "Usage: dtools <command> <pattern> [<pattern> [<pattern> [...]]]"; return 1; fi | |
local tokens=($@) | |
local command=${tokens[0]} | |
local cid=$(find_container ${tokens[@]:1}) | |
case "$command" in | |
log|logs) | |
docker logs $cid | |
;; | |
tail|follow) | |
docker logs -f --tail=0 $cid | |
;; | |
shell|sh) | |
docker_exec $cid sh | |
;; | |
bash) | |
docker_exec $cid bash | |
;; | |
rails) | |
docker_exec $cid "rails console" | |
;; | |
inspect) | |
docker inspect $cid | |
;; | |
id|find) | |
# Nothing to do since we're already printing out the id after lookup. | |
;; | |
show) | |
docker ps | grep $cid | |
;; | |
*) | |
echo "Unknown subcommand $command" | |
return 1 | |
;; | |
esac | |
} | |
main $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment