Skip to content

Commit 114406f

Browse files
committed
feat(docker): add ps script
1 parent 49192b2 commit 114406f

File tree

1 file changed

+73
-0
lines changed
  • scripts/docker

1 file changed

+73
-0
lines changed

Diff for: scripts/docker/ps

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#!/usr/bin/env bash
2+
3+
set -euo pipefail
4+
5+
source "$DOTFILES_PATH/scripts/core/_main.sh"
6+
7+
##? List all containers
8+
##?
9+
##? Usage:
10+
##? ps
11+
docs::parse "$@"
12+
13+
RESET="\e[0m"
14+
BOLD="\e[1m"
15+
CYAN="\e[36m"
16+
YELLOW="\e[33m"
17+
GREEN="\e[32m"
18+
MAGENTA="\e[35m"
19+
BLUE="\e[34m"
20+
UNDERLINE="\e[4m"
21+
22+
declare -a headers=("Name" "Image" "Status" "Created")
23+
declare -a colors=("$CYAN" "$YELLOW" "$GREEN" "$MAGENTA" "$BLUE")
24+
25+
get_column_widths() {
26+
local data="$1"
27+
local -a widths
28+
for i in $(seq 0 $((${#headers[@]} - 1))); do
29+
widths[$i]=$(echo "$data" | awk -F'|' -v col=$((i + 1)) '{print length($col)}' | sort -nr | head -n1)
30+
widths[$i]=$((widths[$i] > ${#headers[$i]} ? widths[$i] : ${#headers[$i]}))
31+
done
32+
echo "${widths[@]}"
33+
}
34+
35+
print_headers() {
36+
local -a widths=("${!1}")
37+
local num_headers=${#headers[@]}
38+
39+
for i in $(seq 0 $((num_headers - 1))); do
40+
if [ "$i" -lt $((num_headers - 1)) ]; then
41+
printf "${UNDERLINE}${BOLD}${colors[$i]}%-${widths[$i]}s ${RESET}" "${headers[$i]}"
42+
else
43+
printf "${UNDERLINE}${BOLD}${colors[$i]}%-${widths[$i]}s${RESET}" "${headers[$i]}"
44+
fi
45+
done
46+
printf "\n"
47+
}
48+
49+
print_data_rows() {
50+
local data="$1"
51+
local -a widths=("${!2}")
52+
local num_headers=${#headers[@]}
53+
54+
echo "$data" | while IFS='|' read -r "${headers[@]}"; do
55+
for i in $(seq 0 $((num_headers - 1))); do
56+
if [ "$i" -lt $((num_headers - 1)) ]; then
57+
printf "${colors[$i]}%-${widths[$i]}s ${RESET}" "${!headers[$i]}"
58+
else
59+
printf "${colors[$i]}%-${widths[$i]}s${RESET}" "${!headers[$i]}"
60+
fi
61+
done
62+
printf "\n"
63+
done
64+
}
65+
66+
docker_data=$(docker ps -a --format "{{.Names}}|{{.Image}}|{{.Status}}|{{.CreatedAt}}" | sort)
67+
68+
# shellcheck disable=SC2034
69+
IFS=' ' read -r -a column_widths <<<"$(get_column_widths "$docker_data")"
70+
71+
# Print headers and data
72+
print_headers column_widths[@]
73+
print_data_rows "$docker_data" column_widths[@]

0 commit comments

Comments
 (0)