Skip to content

Instantly share code, notes, and snippets.

@jhriv
Last active May 20, 2025 21:35
Show Gist options
  • Save jhriv/d9e0cbb3a6baa5b6b842b7e306d32ebb to your computer and use it in GitHub Desktop.
Save jhriv/d9e0cbb3a6baa5b6b842b7e306d32ebb to your computer and use it in GitHub Desktop.
alpine
#!/usr/bin/env zsh
# This can be used an autoloaded zsh funtion as well
# Symlink an image name to this file, such as archlinux, centos_7, debian or ubuntu
# A "_" is replaced with ":", so centos_7 runs the centos:7 image
# However, it cannot be sourced
[[ $ZSH_EVAL_CONTEXT =~ :file$ ]] \
&& { echo 'Do not source this script.'; return 1 }
# cri, Container Runtime Interface
local \
all_containers \
cri \
cri_args \
cri_candidate \
cri_extra_args \
cri_interactive \
exit_status \
highlight \
hostname \
image \
name \
removed \
shell
local cri_candidates=(docker podman)
local status_color=cyan
local success_color=cyan
local failure_color=red
typeset -a \
all_containers \
cri_args \
cri_extra_args \
cri_interactive
image="${${0##*/}/_/:}"
hostname="${image/:/}"
cri_interactive=(--interactive --tty)
# alpine lacks bash, the preferred interactive shell
case $image in
alpine) shell=/bin/sh ;;
*) shell=/bin/bash ;;
esac
for cri_candidate in $cri_candidates; do
if command -v $cri_candidate &>/dev/null; then
cri=$cri_candidate
break
fi
done
if [[ -z $cri ]]; then
echo 'No.'
return 1
fi
while [[ "$1" ]]; do
case $1 in
--) shift; break ;;
:*) image=$image$1; shift ;;
--name) name=$2; shift; shift ;;
--hostname) hostname=$2; shift; shift ;;
-d|--detach) unset cri_interactive; cri_extra_args+=($1); shift ;;
--help) echo "Use \"$cri container --help\" for help. Don't ask me.";
return 1 ;;
-i|--interactive|-t|--tty) shift ;;
--init \
|--no-healthcheck \
|--oom-kill-disable \
|--privileged \
|--read-only \
|--sig-proxy) cri_extra_args+=($1); shift ;;
--rm) cri_extra_args+=($1); removed=true; ;shift ;;
-*) cri_extra_args+=($1 $2); shift; shift ;;
*) break ;;
esac
done
if [[ -z $name ]]; then
name="$hostname-${1:+${1##*/}-}$(date +%Y-%m-%d-%H.%M.%S)"
fi
# cri_extra_args+=($cri_interactive)
cri_args=(
run
$cri_extra_args
$cri_interactive
--name $name
--hostname $hostname
$image
${@-$shell}
)
all_containers=($($cri container ls --no-trunc --all --format '{{.Names}}'))
print -P "%F{$status_color}==>%f $name"
# get (I)ndex with (e)xact match
if (( $all_containers[(Ie)$name])); then
print -P "%F{$status_color}==>%f attaching to existing container"
cri_args=(start --attach --interactive $name)
fi
$cri $cri_args
exit_status=$?
(( exit_status )) && highlight=$failure_color || highlight=$success_color
print -P "%F{$highlight}<==%f $name${removed:+ (removed)}"
return $exit_status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment