Interpretation of UNIX command

what does the below do.

echo * | xargs ls | wc �l

echo * - Output a string comprising the name of each file in the working directory, with each name separated by a space.

xargs ls - construct argument list command

wc -l - it will pipe the output to the wc command, which will display a count of the number of words in the output

The first pipe is an expensive (and error prone) way to mimic the behaviour of ls * ; not sure what it should be good for.
wc -l yields the count of lines, not words.
Please note that options to any command are introduced by a - (minus sign), NOT a (Unicode U+2014, "EM DASH") character which leads to a syntax error.

Why not just:-

ls -1 | wc -l

This negates the need for xargs entirely.

Like RudiC says, using echo * is prone to error.

Robin

Another way to count the number of (non-hidden) entries in a directory in pure shell, which is also more accurate (it will count filenames that contain newlines correctly):

set -- *; echo $#

or

nof () { echo $# ;}; nof *

Unless the directory is empty. Then these options report 1 instead of zero..

To mitigate these corner cases, in bash 4 one can use :

shopt -s nullglob

so that * expands to the null string if the directory is empty (except for hidden files).

or one could try something like:

nof () { 
  if [ -e "$1" ]; then
    echo $#
  else
    echo 0
  fi
}
nof *

--

Note: this could be shortened still to

ls | wc -l

Since -1 is the default option of ls when the output is not a terminal

2 Likes

Just a small observation on the side: "-1" is unnecessary in this case, because ls will format its output in only one (instead of several) columns already if it notices that the output is not going to a terminal. See the following transcript:

# uname -srv
AIX 1 7

# for i in a b c d e ; do touch $i ; done

# ls -l
total 0
-rw-r--r--    1 bakunin     staff             0 Sep 26 17:27 a
-rw-r--r--    1 bakunin     staff             0 Sep 26 17:27 b
-rw-r--r--    1 bakunin     staff             0 Sep 26 17:27 c
-rw-r--r--    1 bakunin     staff             0 Sep 26 17:27 d
-rw-r--r--    1 bakunin     staff             0 Sep 26 17:27 e

# ls
a  b  c  d  e

# ls | cat -
a
b
c
d
e

I hope that helps.

bakunin