If you do much bash scripting then you know there are some pretty nifty tricks you can pull off with it. Bash is a very flexible tool. Most Linux users don't realize how powerful it is and rarely use it. But when you do need it, it is always there. I play around with bash a lot and employ it for a number of things. The command line is certainly my friend. From the command you do do just about anything - but sometimes the simplest thing, say counting files in a directory, can elude you. To do this as a command you would issue something like ls -1 ~/ | wc -l. Not always easy to remember. But say you could create a simple bash script that would count the number of files in a directory as well as list those files. Now that would be cool...and applicable.
In this article I am going to introduce you to a simple bash script that will do just that: Count and list the number of files in a directory. The bash script is fairly simple and takes advantage of arrays.
What is an array?
If you're not sure what an array is, fear not. An array is just a systematic arrangement of objects. This arrangement is usually in rows and columns. Of course there are much more complicated definitions of arrays...especially when applied to application programming. But for the sake of this bash script, it's safe to stop at that definition.
The script for the array is fairly simple. Figure 1 displays how the script will look as you edit it in your favorite editor. And for your copy/paste pleasure, I give you the actual code itself:
Advertising revenue is falling fast across the Internet, and independently-run sites like Ghacks are hit hardest by it. The advertising model in its current form is coming to an end, and we have to find other ways to continue operating this site.
We are committed to keeping our content free and independent, which means no paywalls, no sponsored posts, no annoying ad formats or subscription fees.
If you like our content, and would like to help, please consider making a contribution:
Ghacks is a technology news blog that was founded in 2005 by Martin Brinkmann. It has since then become one of the most popular tech news sites on the Internet with five authors and regular contributions from freelance writers.