Search code examples
bashoutputstorenul

How to store NUL output of a program in bash script?


Suppose there is a directory 'foo' which contains several files:

ls foo:
1.aa 2.bb 3.aa 4.cc

Now in a bash script, I want to count the number of files with specific suffix in 'foo', and display them, e.g.:

SUFF='aa'
FILES=`ls -1 *."$SUFF" foo`
COUNT=`echo $FILES | wc -l`
echo "$COUNT files have suffix $SUFF, they are: $FILES"

The problem is: if SUFF='dd', $COUNT also equal to 1. After google, the reason I found is when SUFF='dd', $FILES is an empty string, not really the null output of a program, which will be considered to have one line by wc. NUL output can only be passed through pipes. So one solution is:

COUNT=`ls -1 *."$SUFF" foo | wc -l`

but this will lead to the ls command being executed twice. So my question is: is there any more elegant way to achieve this?


Solution

  • $ shopt -s nullglob
    $ FILES=(*)
    $ echo "${#FILES[@]}"
    4
    $ FILES=(*aa)
    $ echo "${#FILES[@]}"
    2
    $ FILES=(*dd)
    $ echo "${#FILES[@]}"
    0
    $ SUFFIX=aa
    $ FILES=(*"$SUFFIX")
    $ echo "${#FILES[@]}"
    2
    $ SUFFIX=dd
    $ FILES=(*"$SUFFIX")
    $ echo "${#FILES[@]}"
    0