Context: while read -u, using dedicated fd to run a command line for each line of a file.
Link: https://stackoverflow.com/a/13941223/15603477

while read -u 7 filename;do
    while [ -z "$ans" ]; do
        read -p "Process file '$filename' (y/n)? " -sn1 foo
        [ "$foo" ] && [ -z "${foo/[yn]}" ] && ans=$foo || echo '??'
    if [ "$ans" = "y" ]; then
        echo Yes
        echo "Processing '$filename'."
        echo No
done 7<file.txt

I don't understand the do block:

    read -p "Process file '$filename' (y/n)? " -sn1 foo
    [ "$foo" ] && [ -z "${foo/[yn]}" ] && ans=$foo || echo '??'

I googled sn1, seems no good result. -z is also not easy to search.
What I know;

"&&" is used to chain commands together, such that the next command is run if and only if the preceding command exited without errors (or, more accurately, exits with a return code of 0).

${parameter/pattern/string} The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string.

but here ${foo/[yn]} don't have replace string.

1 Answer 1


Reading man bash


-s Silent mode. If input is coming from a terminal, characters are not echoed.

-n nchars read returns after reading nchars characters rather than waiting for a complete line of input, but honors a delimiter if fewer than nchars characters are read before the delimiter.

The code read -p "Process file '$filename' (y/n)? " -sn1 foo prints the prompt and reads a single char without echoing input.

-z string True if the length of string is zero.

${parameter/pattern/string} ... If string is null, matches of pattern are deleted and the / following pattern may be omitted.

The code [ "$foo" ]&& [ -z "${foo/[yn]}" ]&& ans=$foo || echo '??'

checks if foo is either y or n otherwise prints '??'

  • I would really appreciate your effort to tell me why -z string == True if the length of string is zero. Since man read there is no -z option. And I already googled -z mean in bash
    – jian
    Dec 23, 2021 at 9:22
  • 1
    Open man bash, search for CONDITIONAL EXPRESSIONS section. I have already quoted -z description in my answer.
    – AlexD
    Dec 23, 2021 at 9:25
  • gnu.org/software/bash/manual/html_node/… Thanks.
    – jian
    Dec 23, 2021 at 9:41

You must log in to answer this question.

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