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.
How do I output a count of all files with “tty” in the filename in the Linux directory that holds files on system devices
ls /dev/tty* | wc -w
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
(Note that this includes not only VGA consoles such as
/dev/tty5, but also serials ports such as
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)?