Skip to content

Instantly share code, notes, and snippets.

@goliathuy
Forked from stantonk/multitail.sh
Created February 22, 2018 13:04
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 goliathuy/e429da6750057029e0f4657fba7d0a77 to your computer and use it in GitHub Desktop.
Save goliathuy/e429da6750057029e0f4657fba7d0a77 to your computer and use it in GitHub Desktop.
Unified tail -f of a log file across multiple hosts via ssh.
#!/bin/bash
# Example input and output (from the bash prompt):
# ./multitail.sh -H use@server -f /var/log/somelog.log
# ./multitail.sh -h "use@server use@server2 use@server3" -f "/var/log/somelogA.log /var/log/somelogB.log"
# ./multitail.sh --host "usu@server usu@server" --file "/var/log/logA.log"
# Based on https://gist.github.com/stantonk/5052027 and /usr/share/doc/util-linux/examples/getopt-parse.bash
# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=$(getopt -o f:h: --long file:,server: \
-n 'example.bash' -- "$@")
FILES=()
SERVERS=()
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"
while true ; do
case "$1" in
-f|--file) FILES+=($2) ; shift 2 ;;
-h|--host) SERVERS+=($2) ; shift 2 ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
echo "Hit CTRL-C to stop"
sleep 0.5
PIDS=""
for host in ${HOSTS[*]}
do
for file in ${FILES[*]}
do
CMD="tail -f ${file}"
echo "ssh ${host} $CMD"
ssh $host $CMD &
PIDS="$PIDS $!"
done
done
trap 'kill $PIDS' SIGINT
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment