2

I am having trouble knowing how to output a count of all files with “tty” in the filename in the Linux directory that holds files on system devices.

  • 1
    You should explain what you have tried so far, that way we can point you in the right direction without doing the homework problem for you. – Patrick Mar 6 '12 at 14:09
1
ls /dev/tty* | wc -w
1

First, you need to figure out a way to list those files. The directory that holds the device files is

/dev

so a command to list those files is

echo /dev/*tty*

(Note that this includes not only VGA consoles such as /dev/tty5, but also serials ports such as /dev/ttyS0 or /dev/ttyUSB0.)

There's a command to count words in a text input: wc. So you can get the count like this:

echo /dev/*tty* | wc

This only works if the file names don't contain any whitespace. The command can be more robust, but still not ideal, if you list the file names line by line and count the lines; this only breaks if the file names contain newlines:

ls /dev/*tty* | wc -l

A more robust method in a script is to obtain the list of file names as a list and count its length. Wildcards expand to a list of names; there's a special case when the list is empty: the wildcard is not expanded.

set -- /dev/*tty*
if [ $# -eq 1 ] && ! [ -e "$1" ]; then
  set --
fi
echo "There are $# matching files"

Exercise: does the snippet above work for any wildcard pattern (i.e. is there a wildcard pattern for which the snippet reports 0 files when there is one or vice versa)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy