Cool bash scripting trick with arrays
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: