Can someone explain how this bash script piece works?
is_text_file() {
perl -e 'exit((-B $ARGV[0])?1:0);' "$1"
}
Thanks.
Perl has file type test operators, which this invokes on its first arg. It then uses a ternary operator to convert True/False to a shell status 0 (isTxt) or 1 (not). The function has no explicit return value, so it returns the status of the perl command itself. Bash itself is doing almost nothing here.
-T File is an ASCII or UTF-8 text file (heuristic guess).
-B File is a "binary" file (opposite of -T).
Note carefully the word "guess".
exit()
which exits the interpreter after running the -B $ARGV[0])?1:0
and $ARGV[0] is the argument passed to it by the $1
and the quotes are single quotes not backquotes. How did it know to tie $1 as an input to exit ?
Commented
Jan 10, 2022 at 23:54
$1
is the first arg to the shell function, it's passed as an arg to Perl which uses $ARGV[0]
to hold the first arg to the script. (Same idea, different name in the two languages.) The Perl script calls the -B
operator/function on that, fixes the returned value into 1 or 0, and passes that to exit()
.