Skip to content

Instantly share code, notes, and snippets.

@gregberns
Last active November 11, 2020 17:44
Show Gist options
  • Save gregberns/2121c81b728d10ea5eb6026dc1734c49 to your computer and use it in GitHub Desktop.
Save gregberns/2121c81b728d10ea5eb6026dc1734c49 to your computer and use it in GitHub Desktop.
wait-for-file.sh
#!/bin/sh
# Wait for a file to exist
# Modeled off this script
# https://gist.github.com/gregberns/7e1254209860632f7a1bf9aa7c7638ee
TIMEOUT=15
QUIET=0
echoerr() {
if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi
}
usage() {
exitcode="$1"
cat << USAGE >&2
Usage:
$cmdname filepath [-t timeout] [-- command args]
-q | --quiet Do not output any status messages
-t TIMEOUT | --timeout=timeout Timeout in seconds, default 10s, zero for no timeout
-- COMMAND ARGS Execute command with args after the test finishes
USAGE
exit "$exitcode"
}
wait_file() {
local file="$1"; shift
local wait_seconds="${1:-10}"; shift # 10 seconds as default timeout
for i in `seq $TIMEOUT` ; do
test -e "$file" > /dev/null 2>&1
# nc -z "$HOST" "$PORT" > /dev/null 2>&1
result=$?
if [ $result -eq 0 ] ; then
if [ $# -gt 0 ] ; then
exec "$@"
fi
exit 0
fi
sleep 1
done
echo "Operation timed out" >&2
exit 1
}
while [ $# -gt 0 ]
do
case "$1" in
*/* )
FILE_PATH=$(printf "%s\n" "$1")
# PORT=$(printf "%s\n" "$1"| cut -d : -f 2)
shift 1
;;
-q | --quiet)
QUIET=1
shift 1
;;
-t)
TIMEOUT="$2"
if [ "$TIMEOUT" = "" ]; then break; fi
shift 2
;;
--timeout=*)
TIMEOUT="${1#*=}"
shift 1
;;
--)
shift
break
;;
--help)
usage 0
;;
*)
echoerr "Unknown argument: $1"
usage 1
;;
esac
done
TIMEOUT=$TIMEOUT || -10
if [ "$FILE_PATH" = "" ]; then
echoerr "Error: you need to provide a file path to check."
usage 2
fi
wait_file "$FILE_PATH" "$TIMEOUT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment