Skip to content

Instantly share code, notes, and snippets.

@s-shin
Last active December 22, 2017 15:15
Show Gist options
  • Save s-shin/510b048e945ca50498b8351e4c42fbd9 to your computer and use it in GitHub Desktop.
Save s-shin/510b048e945ca50498b8351e4c42fbd9 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -eu
: ${IO_RUNNING_FILE:=.io_running}
: ${IO_STDIN_FILE:=.io_stdin}
: ${IO_STDOUT_FILE:=.io_stdout}
io.help() {
cat <<EOT
Usage: io <command> [<args>]
Commands:
run <command and args>
info
quit
echo <any echo args>
cat <any cat args>
tail <any tail args>
stdin
stdout
EOT
}
is_running() {
[[ -f "$IO_RUNNING_FILE" || -f "$IO_STDIN_FILE" || -f "$IO_STDOUT_FILE" ]]
}
cleanup() {
rm -f "$IO_RUNNING_FILE" "$IO_STDIN_FILE" "$IO_STDOUT_FILE"
}
abort_if_running() {
if is_running; then
>&2 echo "ERROR: Command has already been running by io."
return 1
fi
}
abort_if_not_running() {
if ! is_running; then
>&2 echo "ERROR: No command is running by io."
return 1
fi
}
io.run() {
abort_if_running
if (($# == 0)); then
>&2 echo "ERROR: No command is specified."
return 1
fi
if ! type "$1" >/dev/null 2>&1; then
>&2 echo "ERROR: Command '$1' is not found."
return 1
fi
echo "$*" >"$IO_RUNNING_FILE"
mkfifo "$IO_STDIN_FILE"
(while [[ -f "$IO_RUNNING_FILE" ]]; do sleep 1; done) >"$IO_STDIN_FILE" &
"$@" <"$IO_STDIN_FILE" >"$IO_STDOUT_FILE" &
}
io.info() {
if is_running; then
echo -n "Running: "
cat "$IO_RUNNING_FILE"
else
echo "Not running."
fi
}
io.quit() {
abort_if_not_running
cleanup
}
io.echo() {
abort_if_not_running
echo "$@" >"$IO_STDIN_FILE"
}
io.cat() {
abort_if_not_running
cat "$@" >"$IO_STDIN_FILE"
}
io.tail() {
abort_if_not_running
tail "$@" "$IO_STDOUT_FILE"
}
io.stdin() {
abort_if_not_running
echo "$IO_STDIN_FILE"
}
io.stdout() {
abort_if_not_running
echo "$IO_STDOUT_FILE"
}
main() {
if (($# == 0)); then
>&2 io.help
return 1
fi
local cmd="$1"; shift
local io_cmd="io.${cmd}"
if type "$io_cmd" >/dev/null 2>&1; then
"$io_cmd" "$@"
else
>&2 echo -e "ERROR: Unknown command '${cmd}'\n"
>&2 io.help
return 1
fi
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment