Linux Topic
   >  Shell Scripts
   >  Using Comments
   >  Passing Arguments to Scripts
   >  Using Conditional Statements
   >  Using Loop Statements
   >  Reading and Writing Files
   >  Script Permissions
   >  Cron and Scheduling
   >  A Scripting Example
   >  Other Scripting Languages

 

Using Arguments in Shell Scripts

Why use Arguments?

Arguments are data that you pass into a script via the command line. What programmers use arguments for is simply to make a script more general purpose (generic) than it would otherwise be if these were hard-coded inside the program itself. One example would be a script that passes in the name of it's input file via an argument, rather than expecting the user to rename the file to the name coded inside the program. Another might be a string value to search for - such as a username,etc. A well thought out argument list is always a good thing and allows a single script to be used for a variety of purposes, rather than having to create (clone) out a new version of the script for each different scenario.


Passing Arguments to Shell Scripts

Anything you type after the name of a Shell script on the run line, will be passed as an argument to the script in a special variable. Each space delimited string will be passed into the script as a variable of the form: $<number> (-for example, $1, $2, $10, etc). Parsing starts at the left (-with parameter $1) and scans to the right (-up to parameter $n). So, if you were to pass in four strings to a script, such as:

$ ./myScript.sh arg1 arg2 "this is arg3" arg4

The script would receive them as:

  • $1 : arg1
  • $2 : arg2
  • $3 : this is arg3
  • $4 : arg4

Note how the quotes stop the string "this is arg3" from being split into 3 different arguments

Note: that the parameter numbering starts at $1. This is because argument $0 has a special meaning - that of the script name, as it was evoked from the command line (e.g. in the example above, it would contain ./myScript.sh).

If you wanted to print out the values of these parameters from inside the script, you could add some simple echo commands, such as:

echo "Script name is $0"
echo "Parameter 1=$1"
echo "Parameter 2=$2"
echo "Parameter 3=$3"
echo "Parameter 4=$4"

Following that, when you run the above script with the same command line as the example above, you should see:

>Script name is ./myScript.sh
Parameter 1=arg1
Parameter 2=arg2
Parameter 3=this is arg3
Parameter 4=arg4

HomeSite IndexDesktop GuideServer GuideHints and TipsHardware CornerVideo SectionContact Us

 sitelock verified Firefox Download Button