Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
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
add comment

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

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

2 Answers

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

share|improve this answer
add comment
ls /dev/tty* | wc -w
share|improve this answer
add comment

Your Answer

 
discard

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