As mentioned already
find is usually the correct tool when handling files. It can however be perfectly OK.
You can skip this part of
printf if you want, only include it as a bonus :P
One thing that you also can start using is
printf. It is generally a better option then
echo. In its simplest form you have:
printf "Some text\n"
\n is new-line. If you want to print some variable you can use the special symbol
%s (for string):
printf "Name is %s \n" "$name"
| +---- value
+---------------- format string
printf "Name is %s city is %s \n" "$name" "$city"
| | |
| +-------+----- values
+------------------------------------ format string
There are other symbols you can use, such as
%d (for digit). You can also use other special characters such as
For you code it is generally better to use the newer
$(cmd) instead of ``cmd`. In your code that would be:
Next thing to look at is the
for loop. Your statement
for n in `ls *.txt`; do
does not do what you think. Here
n is treated as a variable name to which the result of
ls *.txt is assigned. If you have the files:
The execution of the code would expand to:
for n in a.txt b.txt c.txt; do
That is: for each iteration
n is set to the next file name. You end up with:
n=a.txt (first loop)
n=b.txt (second loop)
n=c.txt (last loop)
If we collect this together we can for example write something like this:
printf "Write the file extension you want to search for: "
printf "Searching for files with extension '%s'\n" "$ext"
for file in *"$ext"; do
printf "File: %s\n" "$file"
Or you can simply say:
Note that the asterisk is outside the quotes. Else it won't expand.