How to pass and use arguments in shell script

Passing arguments

The capability of passing arguments to the script brings dynamic features to the scripts. In shell scripting, the arguments are provided to the script at the time of execution/running of the command.

Syntax

./script.sh argument-1, argument-2, ..., argument-n

Using arguments

Inside the script, we can use the $ symbol followed by the integer to access the arguments passed. For example, $1, $2, and so on. The $0 will contain the script name.

Example

Let’s consider an example where we pass three arguments to the script (arg.sh) and print them.

#!/bin/bash
echo "The file name: $0."
echo "The first argument is $1."
echo "The second argument is $2."
echo "The third argument is $3."

Note: The echo in shell scripting is used to print the contents to the terminal.

We execute the script as follows:

./arg.sh first_argument second_argument third_argument

We get the following output:

root@educative:/# ./arg.sh first_argument argument2 3rd
The file name: ./arg.sh.
The first argument is first_argument.
The second argument is second_argument.
The third argument is third_argument.

To try the command yourself, we need to create a file and provide it execute permission. Follow the steps given below:

  • Step1: We type vi arg.sh in the terminal to open the vi editor in Linux.

  • Step2: Press the i key to enter insert mode.

  • Step3: Copy the code shown at the beginning of the example section and paste it into the terminal.

  • Step4: Press the esc key to go into the command mode on the editor.

  • Step5: Press the shift + : key together and type wq, such as write and quit. This will save the file and take us back to the command line.

  • Step 6: Run the command chmod u+x arg.sh to make the file executable.

  • Step 7: Run the command ./arg.sh first_argument argument2 3rd to see the results.

Terminal 1
Terminal
Loading...

Free Resources