自己用到的一些 Shell 脚本片段
Feb 23, 2020 21:30 · 413 words · 1 minute read
检查应用程序是否已安装:
command_exists() {
command -v "$@" >/dev/null 2>&1
}
check_tools() {
# Parse arguments
if [ $# -gt 0 ]; then
for i in $@; do
if ! command_exists $i; then
echo "$i is not installed, please install $i first."
exit 1
fi
done
fi
}
check_tools go docker
从 Docker Hub 获取某个 org 下的所有镜像和 tag:
PAGE_SIZE=100
ORG=""
fetch_images() {
repos=$(curl -s -H 'Content-Type: application/json' -X GET https://hub.docker.com/v2/repositories/${ORG}/?page_size=${PAGE_SIZE} | jq -r '.results|.[]|.name')
for repo in ${repos}; do
tag=$(curl -s -H 'Content-Type: application/json' -X GET https://hub.docker.com/v2/repositories/${ORG}/${repo}/tags/?page_size=${PAGE_SIZE} | jq -r '.results|.[]|.name')
echo "${ORG}/${repo}:${tag}"
done
}
倒计时:
countdown() {
seconds_left=$1
echo "waiting $seconds_left second(s)..."
while [ $seconds_left -gt 0 ]; do
echo -n $seconds_left
sleep 1
seconds_left=$(($seconds_left - 1))
echo -ne "\r"
done
}
countdown 20
OS 检测:
if [[ "$OSTYPE" == "linux-gnu" ]]; then
echo "Linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
echo "macOS"
else
echo "Unknown OS"
fi
获取容器命名空间
#!/bin/bash
#
# dockerpsns - proof of concept for a "docker ps --namespaces".
#
# USAGE: ./dockerpsns.sh
#
# This lists containers, their init PIDs, and namespace IDs. If container
# namespaces equal the host namespace, they are colored red (this can be
# disabled by setting color=0 below).
#
# Copyright 2017 Netflix, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 10-Apr-2017 Brendan Gregg Created this.
namespaces="cgroup ipc mnt net pid user uts"
color=1
declare -A hostns
printf "%-14s %-20s %6s %-16s" "CONTAINER" "NAME" "PID" "PATH"
for n in $namespaces; do
printf " %-10s" $(echo $n | tr a-z A-Z)
done
echo
# print host details
pid=1
read name < /proc/$pid/comm
printf "%-14s %-20.20s %6d %-16.16s" "host" $(hostname) $pid $name
for n in $namespaces; do
id=$(stat --format="%N" /proc/$pid/ns/$n)
id=${id#*[}
id=${id%]*}
hostns[$n]=$id
printf " %-10s" "$id"
done
echo
# print containers
for UUID in $(docker ps -q); do
# docker info:
pid=$(docker inspect -f '{{.State.Pid}}' $UUID)
name=$(docker inspect -f '{{.Name}}' $UUID)
path=$(docker inspect -f '{{.Path}}' $UUID)
name=${name#/}
printf "%-14s %-20.20s %6d %-16.16s" $UUID $name $pid $path
# namespace info:
for n in $namespaces; do
id=$(stat --format="%N" /proc/$pid/ns/$n)
id=${id#*[}
id=${id%]*}
docolor=0
if (( color )); then
[[ "${hostns[$n]}" == "$id" ]] && docolor=1
fi
(( docolor )) && echo -e "\e[31;1m\c"
printf " %-10s" "$id"
(( docolor )) && echo -e "\e[0m\c"
done
echo
done