0

Can someone explain how this bash script piece works?

is_text_file() { 
    perl -e 'exit((-B $ARGV[0])?1:0);' "$1"
}

Thanks.

1 Answer 1

2

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".

4
  • ref. perldoc.perl.org/perlfunc#-X-FILEHANDLE
    – ilkkachu
    Commented Jan 10, 2022 at 23:43
  • ok, I think I got it. -e means to execute a command. The command is 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
    @user3161924, $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().
    – ilkkachu
    Commented Jan 11, 2022 at 0:13
  • 1
    okay, so items outside the single quotes are parameters to the command after the -e. Thanks! Commented Jan 11, 2022 at 0:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .