Unix – Command line Arguments

By -

What is command line argument?

  • Those values which we pass at the time of running the shell scripts are known as Command line values(arguments). Command line arguments are treated as special variables within the script. They can be changed with the shift command.
  • The command line arguments are enumerated in the following manner $0, $1, $2, $3, $4, $5, $6, $7, $8 and $9.
  • 0 is special in that it corresponds to the name of the script itself.
  • $1 is the first argument, $2 is the second argument and so on.

Point to Remember: To reference after the ninth argument you must enclose the number in brackets like this ${nn}.

You can use the shift command to shift the arguments 1 variable to the left so that $2 becomes $1, $1 becomes $0 and so on, $0 gets scrapped because it has nowhere to go, this can be useful to process all the arguments using a loop, using one variable to reference the first argument and shifting until you have exhausted the arguments list.

Built-In command-line parameters:

  • $# represents the parameter count. It is useful for the loop structure to process each argument.
  • $@ expands to all the parameters separated by spaces (single-dimensional array like). With this $@ we can pass these values to another program or function.
  • $$ returns the process id of the shell invoked to execute shell script.
Paresh Mayani

Lazy android developer, exploring the horizon of android development since 7 years, currently working as a Technical Lead - Android at Simform Solutions, India. Former Application Architect at KarConnect. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

Loading Facebook Comments ...
Loading Disqus Comments ...