Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

migrated from stackoverflow.com Mar 6 '12 at 14:02

This question came from our site for professional and enthusiast programmers.

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
ls /dev/tty* | wc -w
share|improve this answer

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


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 --
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)?

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.