

One use case of PID is to append it when creating temporary files from the script.Įxample #3: Write a Shell Script to print the PID of the currently running script #!/bin/sh This variable holds the PID i.e., Process IDentifier of the currently running script. # and passing number of arguments passed to the script # function to check number of arguments passed to the script In the following example we are checking if argument was provided based on return code from a function call. So, for example if we call a function that is supposed to return any value back then we can get that returned value using the $? variable.Įxample #2: Write a Shell Script to display some result based on return value from a function call This variable holds the exit value of the last run command or return code from a function. Then, inside the body of the for loop we echo each of the arguments. If the user provides 1 or more number of arguments to the script file then $# is greater than 0 and so, we use the for loop to pick each argument stored in variable and assign it to variable arg. If $# is 0 then we echo No argument provided to the script. We are using if statement to check if the user provided any argument to the script. We are using the $# command to get the total number of arguments passed to the script file. In the above script we are using the $0 variable to get the name of the script file i.e., example01.sh. Total number of arguments passed to the script = 5 $ sh example01.sh My name is Yusuf Shakeel Total number of arguments passed to the script = 0 The name of the script file is example01.sh # display all the arguments using for loopĮcho "No argument provided to the script."

# display total number of arguments passed to the scriptĮcho "Total number of arguments passed to the script = $#" They both holds the list of arguments provided to the script.Įxample #1: Write a Shell Script to take user data as command line argument and display a greetings message #!/bin/sh This variable hold the total number of arguments passed to the script. These variables hold the arguments provided to the script. There are some special variables that we get to handle command line arguments in shell programming. In the above example, greetings.sh is the script file. Where, filename.sh is a shell script file and argument1, argument2.

Syntax $ sh filename.sh argument1 argument2. We use command line arguments to provide input to shell script. In this tutorial we will learn how to handle command line arguments in Shell Programming.
