Consider the following command:
ls a command we’re all familiar with.
Everything after
ls
in the above command are command-line parameters to the ls executable.
NOTE:
ls
is a compiled binary executable, written in c and compiled to executable machine code. Not a shell-script. But the concept of command line parameters is the same for pre-compiled binaries as it is for executable scripts. They are parameters which are passed to the script/program at runtime, when the program/script is ran.
Going back to the ls example :
-Alh
is a group of three parameters, telling the ls command how to format the output. (A = Almost all - lists everything except . and .., l = long list format, h = human-readable file-sizes e.g. 64k, 1Mb, 2.3Gb etc.)
And the path at the end of the command is a parameter telling ls the directory we want to list the contents of.
Sometimes parameters are mandatory, other times parameters are optional.
Sometimes programs/script require a fixed number of mandatory parameters. And sometimes they even expect them in a fixed order too!
It all depends on the script/program and the choices made by the programmers who created it.
for example, the ls command can be ran without any parameters. All parameters to it are optional and they don’t have to be specified in a fixed order either.
When writing your own scripts, adding support for command line parameters can make your scripts more flexible - allowing them to be used in multiple situations.
So for example if I was writing a script called findandmove to search /home/Jason/Downloads/ for .png files and move them to /home/jason/Pictures/png
If I chose to hard code the search path and the file extension and the output directory directly into the script - my script will only be useful for that one very specific task.
But if I set up my script to accept those things as parameters,
E.G.
findandmove {search path} {file pattern} {output path}
I’m no longer constrained to only finding png files in my Downloads directory and moving them to another directory.
Now I could run my script and tell it to search /media/jason/4Tb/ for all .mp4 files and move them to /home/jason/Videos/
Or I could search for text files in my Documents directory and move them to a backup drive.
And I could even add an optional parameter that would copy the files instead of moving them.
So now, thanks to parameters - my one script is still doing a very specific task - but it can be used in different contexts/situations, so it’s more flexible.