Skip to content

Instantly share code, notes, and snippets.

@siberex
Last active May 28, 2020 15:12
Show Gist options
  • Select an option

  • Save siberex/d1c07389333d9cdb1c9e6853ec70c98b to your computer and use it in GitHub Desktop.

Select an option

Save siberex/d1c07389333d9cdb1c9e6853ec70c98b to your computer and use it in GitHub Desktop.
Wait for file to become readable
#!/usr/bin/env bash
# https://gist.github.com/siberex/d1c07389333d9cdb1c9e6853ec70c98b
# Wait for file to become readable
# Similar to https://github.com/vishnubob/wait-for-it
# Usage:
# wait-for-file.sh -t 10 -p /tmp/something -- echo "ok"
WAITFORIT_cmdname=${0##*/}
echoerr() { echo "$@" 1>&2; }
usage() {
cat <<USAGE >&2
Usage:
$WAITFORIT_cmdname -p /path/to/file [-t timeout] [-- command args]
-p PATH | --path=PATH Path to test for readability
-t TIMEOUT | --timeout=TIMEOUT Timeout in seconds, default is 15
-- COMMAND ARGS Execute command with args after the test finishes
USAGE
exit 1
}
# Exit script when command fails
set -o errexit
# Return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status
set -o pipefail
# process arguments
while [[ $# -gt 0 ]]; do
case "$1" in
-t)
WAITFORIT_TIMEOUT="$2"
if [[ $WAITFORIT_TIMEOUT == "" ]]; then break; fi
shift 2
;;
--timeout=*)
WAITFORIT_TIMEOUT="${1#*=}"
shift 1
;;
-p)
WAITFORIT_PATH="$2"
if [[ $WAITFORIT_PATH == "" ]]; then break; fi
shift 2
;;
--path=*)
WAITFORIT_PATH="${1#*=}"
shift 1
;;
--)
shift
WAITFORIT_CLI=("$@")
break
;;
--help)
usage
;;
*)
echoerr "Unknown argument: $1"
usage
;;
esac
done
if [[ "$WAITFORIT_PATH" == "" ]]; then
echo "Error: you need to provide a path to test."
usage
fi
# Default is 15 seconds
WAITFORIT_TIMEOUT=${WAITFORIT_TIMEOUT:-15}
WAITFORIT_start_ts=$(date +%s)
if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
echo "$WAITFORIT_cmdname: waiting $WAITFORIT_TIMEOUT seconds for readability: $WAITFORIT_PATH"
else
if [ -r "$WAITFORIT_PATH" ]; then
WAITFORIT_TIMEOUT=-1
else
WAITFORIT_TIMEOUT=0
fi
fi
while [[ $WAITFORIT_TIMEOUT -gt 0 ]]; do
if [ -r "$WAITFORIT_PATH" ]; then
WAITFORIT_TIMEOUT=-1
break
fi
sleep 1
WAITFORIT_TIMEOUT=$((WAITFORIT_TIMEOUT - 1))
done
if [[ $WAITFORIT_TIMEOUT -eq -1 ]]; then
WAITFORIT_end_ts=$(date +%s)
echo "$WAITFORIT_cmdname: $WAITFORIT_PATH is available after $((WAITFORIT_end_ts - WAITFORIT_start_ts)) seconds"
# shellcheck disable=SC2128
if [[ $WAITFORIT_CLI != "" ]]; then
exec "${WAITFORIT_CLI[@]}"
else
exit 0
fi
else
echoerr "Timeout"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment