Skip to content

Instantly share code, notes, and snippets.

@elundmark
Last active October 13, 2022 16:11
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 elundmark/99a335084c2d86892815389073759cc1 to your computer and use it in GitHub Desktop.
Save elundmark/99a335084c2d86892815389073759cc1 to your computer and use it in GitHub Desktop.
Using the test command with STDIN
#!/usr/bin/env bash
set +H
# Using STDIN, check LINES of FILES and use the test command to filter by EXPRESSION
# Supports all EXPRESSIONS that test does.
# fn | test_stdin -f \! -d -L -s \! -ot FILEARG
# Use '!' to negate results. -ef, -ot, -nt will be read as "LINE -nt FILEARG"
if [[ $# -eq 0 ]] ; then
# An omitted EXPRESSION defaults to false (see manpage for test)
exit 1
fi
validate_file(){
local f="$1"
shift
local -a flags=("${@}")
local -i passed=0 must_match=$# i=0
for (( i = 0; i < $#; i++ )); do
if [[ "${flags[i]}" = '!' ]] ; then
i=$((i+1))
must_match=$((must_match-1))
if [[ "${flags[i]}" =~ ^-(ef|nt|ot)$ ]] ; then
i=$((i+1))
must_match=$((must_match-1))
if ! test "$f" "${BASH_REMATCH[0]}" "${flags[i]}" ; then
passed=$((passed+1))
fi
elif ! test "${flags[i]}" "$f" ; then
passed=$((passed+1))
fi
continue
elif [[ "${flags[i]}" =~ ^-(ef|nt|ot)$ ]] ; then
i=$((i+1))
must_match=$((must_match-1))
if test "$f" "${BASH_REMATCH[0]}" "${flags[i]}" ; then
passed=$((passed+1))
fi
continue
fi
if test "${flags[i]}" "$f" ; then
passed=$((passed+1))
fi
done
return "$((must_match-passed))"
}
declare -i e_c=0
while read -r; do
if validate_file "$REPLY" "${@}" ; then
printf '%s\n' "$REPLY"
else
e_c=1
fi
done
exit "$e_c"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment