Skip to content

Instantly share code, notes, and snippets.

@hypersoft
Last active December 13, 2015 19:18
Show Gist options
  • Save hypersoft/4961455 to your computer and use it in GitHub Desktop.
Save hypersoft/4961455 to your computer and use it in GitHub Desktop.
I/O function callback shell.
lib.read.for ()
{
# Usage: lib.read.for [line|char|record delimiter "char"] [do command] [in file ...]
declare -A env[line]=0 env[delimited]=0 env[binary]=0; declare -i EOF;
if [[ "$1" == char ]]; then env[binary]=1; shift;
elif [[ "$1" == line ]]; then env[line]=1; shift;
elif [[ "$1$2" == recorddelimiter ]]; then env[delimited]=1 env[delimiter]="$3";
shift 2; shift; fi;
[[ "$_" == shift ]] && {
[[ $? && "$1" == do ]] && { env[command]="$2"; shift 2; };
[[ $? && "$1" == in ]] && shift;
}; (($#)) || set -- /dev/stdin; (( env[binary] )) && {
declare file char; [[ -n "${env[command]}" ]] && {
for file; do EOF=0; while (( ! EOF )); do
read -rN1 char; EOF=$?; true;
${env[command]} "$char" || return;
done <"$file"; done; return;
} || {
for file; do while read -rN1 char; do
printf "%c" "$char"; done <"$file";
done; return;
}
} || (( env[line] )) && {
declare file line; [[ -n "${env[command]}" ]] && {
for file; do while IFS='' read -r line; do
EOF=0 ${env[command]} "$line" || return; done <"$file";
EOF=1 ${env[command]} "$line";
done; return;
} || { "$BASH_SOURCE: $FUNCNAME: $LINENO: error: set line: callback";
return;
}
} || (( env[delimited] )) && {
declare file record; [[ -n "${env[command]}" ]] && {
for file; do while IFS='' read -rd "${env[delimiter]}" record; do
EOF=0 ${env[command]} "$record" || return; done <"$file";
EOF=1 ${env[command]} "$line";
done; return;
} || { "$BASH_SOURCE: $FUNCNAME: $LINENO: error: set delimited: callback";
return;
}
} || {
declare file content; [[ -n "${env[command]}" ]] && {
for file; do IFS='' read -rN0 content <"$file";
${env[command]} '%s' "$content" || return;
done; return;
} || \
for file; do IFS='' read -rN0 content <"$file"; printf '%s' "$content"; done;
};
}
@hypersoft
Copy link
Author

Improved EOF handling. Of course, one must test for EOF, and determine the proper output format based on that condition. char mode only returns EOF if there is no more data to read.

Line mode, and record mode, will set EOF=1 and return the last record.

Line mode and record mode do the same thing, so line mode may possibly become deprecated for a recursive call to self OR line mode parameter setup under record mode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment