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
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:
array=(`ls`)
Would you mind sharing that wallpaper? :D
I’ve stopped using bash for most of my command line programming. Instead I favour fish. The fish shell offers much more flexibility, power and consistency.
Your given example can be accomplished with:
count ls *
I even have compiled it on my DNS-323 Nas.
I highly recommend you check it out.
fishshell.org
Personally I find it much easier to use the ‘find’ command for almost anything like this as you can easily find out how many files there are of a certain type or name.
Can be done on one line also
x=0; for i in `find . -maxdepth 1 -type f`; do let x++; done; echo $x