From a comment you wrote:
im in college for linux administrator and 1 of my current classes in shell scripting. My teacher is just going over basic stuff. And, my current assingment is to get the number of files in the tmp directory of our class server, the number of files that end in .log and the number of files that only have 1 character names and store the data in a file and then display the stored data to the user. I know it's stupid, but it's my assignment.
I only hope that they don't teach you to parse the output of ls
in college... it's one of the most terrible things to do. Please refer to these links:
The solution you chose
ls /mydir/? /mydir/?.* | wc -l
is broken in two cases:
- If there are no matching files, you'll get an error. You can fix that in two ways: use
shopt -s nullglob
or just redirect stderr
to devnull
.
- If there's a newline in a file name. Try it:
touch $'a.lol\nlol\n\lol\nlol\nlol'
. LOL.
The proper bash way is the following:
shopt -s nullglob
shopt -u failglob
files=( /mydir/? /mydir/?.* )
echo "There are ${#files[@]} files found."