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.
./script.sh argument-1, argument-2, ..., argument-n
Inside the script, we can use the
$ symbol followed by the integer to access the arguments passed. For example,
$2, and so on. The
$0 will contain the script name.
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."
echoin 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:
vi arg.shin the terminal to open the vi editor in Linux.
ikey to enter insert mode.
esckey to go into the command mode on the editor.
shift + :key together and type
wq, such as write and quit. This will save the file and take us back to the command line.
arg.shto make the file executable.
./arg.sh first_argument argument2 3rdto see the results.
View all Courses