Skip to content

Instantly share code, notes, and snippets.

@kotet
Created January 28, 2021 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kotet/5cea4c15463718861406d8801a9e07c1 to your computer and use it in GitHub Desktop.
Save kotet/5cea4c15463718861406d8801a9e07c1 to your computer and use it in GitHub Desktop.
コマンドキュー
#!/usr/bin/env bash
# https://betterdev.blog/minimal-safe-bash-script-template/
set -Eeuo pipefail
trap cleanup SIGINT SIGTERM ERR EXIT
usage() {
cat <<EOF
Usage: $(basename "${BASH_SOURCE[0]}") [command]
EOF
exit
}
SOCKET="/tmp/kotet-q.sock"
FIFO="$(mktemp -u)"
SERVER_MODE=0
cleanup() {
trap - SIGINT SIGTERM ERR EXIT
# script cleanup here
[[ ${SERVER_MODE} -eq 1 ]] && rm -f ${SOCKET}
[[ ${SERVER_MODE} -eq 1 ]] && rm -f ${FIFO}
}
setup_colors() {
if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
NOFORMAT='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' BLUE='\033[0;34m' PURPLE='\033[0;35m' CYAN='\033[0;36m' YELLOW='\033[1;33m'
else
NOFORMAT='' RED='' GREEN='' ORANGE='' BLUE='' PURPLE='' CYAN='' YELLOW=''
fi
}
msg() {
echo >&2 -e "${1-}"
}
die() {
local msg=$1
local code=${2-1} # default exit status 1
msg "$msg"
exit "$code"
}
parse_params() {
while :; do
case "${1-}" in
-h | --help) usage ;;
-v | --verbose) set -x ;;
--no-color) NO_COLOR=1
;;
-?*) die "Unknown option: $1" ;;
*) break ;;
esac
shift
done
command=("$@")
return 0
}
parse_params "$@"
setup_colors
if test -S "${SOCKET}"; then
[[ ${#command[@]} -eq 0 ]] && die "Missing script arguments"
echo "${command[*]-}" | nc -U ${SOCKET}
msg "${GREEN}the command added to queue: ${command[*]-}${NOFORMAT}"
exit
fi
SERVER_MODE=1
msg "${GREEN}Listening on ${SOCKET} ...${NOFORMAT}"
mkfifo ${FIFO}
(
while true; do
nc -U -l ${SOCKET} | ( read line; echo ${line} > ${FIFO} )
done
) &
while true; do
line=$(cat ${FIFO})
msg "${GREEN}Q: ${line}${NOFORMAT}"
${line}
done
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment