0% found this document useful (0 votes)
7 views2 pages

Command Line Argument

Command-line arguments in shell scripting allow users to pass inputs to scripts during execution, accessed through special variables like $0 for the script name and $1, $2 for subsequent arguments. The document provides examples of using these arguments in scripts, including a simple echo script and a script to sum two numbers. Key takeaways include the representation of the script name, individual arguments, the total number of arguments, and how to check if arguments are provided.

Uploaded by

Raghuraman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Command Line Argument

Command-line arguments in shell scripting allow users to pass inputs to scripts during execution, accessed through special variables like $0 for the script name and $1, $2 for subsequent arguments. The document provides examples of using these arguments in scripts, including a simple echo script and a script to sum two numbers. Key takeaways include the representation of the script name, individual arguments, the total number of arguments, and how to check if arguments are provided.

Uploaded by

Raghuraman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Command Line Arguments in Shell Scripting

What are Command Line Arguments?


Command-line arguments allow passing inputs to a shell script when executing it.
These arguments are accessed using special variables like $0, $1, $2, ..., and
so on.

How Command Line Arguments Work?


1. $0 → Represents the script name.
2. $1, $2, ... → Represent the first, second, and subsequent arguments.
3. $# → Gives the number of arguments passed.
4. $* and $@ → Store all arguments as a single string.

Example: Simple Script Using Arguments


#!/bin/bash
echo "Script Name: $0"
echo "First Argument: $1"
echo "Second Argument: $2"
echo "Number of Arguments: $#"
echo "All Arguments: $@"

Execution:
bash script.sh Hello World

Output:
Script Name: script.sh
First Argument: Hello
Second Argument: World
Number of Arguments: 2
All Arguments: Hello World
Example: Sum of Two Numbers
#!/bin/bash
sum=$(( $1 + $2 ))
echo "Sum of $1 and $2 is: $sum"

Execution:
bash add.sh 10 20

Output:
Sum of 10 and 20 is: 30

Checking If Arguments Are Provided


#!/bin/bash
if [ $# -eq 0 ]; then
echo "No arguments provided!"
exit 1
fi
echo "You entered: $@"

Execution:
bash check.sh

Output:
No arguments provided!

Key Takeaways
Command-line arguments help pass dynamic inputs.
$0 represents the script name.
$1, $2, ... store individual arguments.
$# gives the number of arguments.
$@ holds all arguments as a list.

You might also like