0
0
Bash Scriptingscripting~15 mins

Command-line arguments ($1, $2, ...) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Command-line Arguments in Bash Scripts
📖 Scenario: You want to create a simple bash script that takes two numbers as input when you run it from the command line. Then, the script will add these two numbers and show the result.This is like when you use a calculator app and enter two numbers to get their sum, but here you will type the numbers next to the script name in the terminal.
🎯 Goal: Build a bash script that reads two numbers from the command line arguments $1 and $2, adds them, and prints the sum.
📋 What You'll Learn
Create a bash script that uses command-line arguments
Use $1 and $2 to get the first and second input numbers
Add the two numbers inside the script
Print the result to the terminal
💡 Why This Matters
🌍 Real World
Many command-line tools accept inputs as arguments. Learning to use <code>$1</code>, <code>$2</code>, etc., helps automate tasks and create flexible scripts.
💼 Career
Understanding command-line arguments is essential for system administrators, DevOps engineers, and anyone writing shell scripts to automate workflows.
Progress0 / 4 steps
1
Create a bash script file
Create a bash script file named add_numbers.sh and add the first line #!/bin/bash to specify the script interpreter.
Bash Scripting
Need a hint?

The first line in a bash script should be #!/bin/bash to tell the system to use bash to run the script.

2
Assign command-line arguments to variables
Inside add_numbers.sh, create two variables called num1 and num2 and assign them the values of the first and second command-line arguments $1 and $2 respectively.
Bash Scripting
Need a hint?

Use num1=$1 and num2=$2 to get the first and second inputs from the command line.

3
Add the two numbers
Add the two variables num1 and num2 using arithmetic expansion and store the result in a variable called sum.
Bash Scripting
Need a hint?

Use sum=$((num1 + num2)) to add the two numbers in bash.

4
Print the sum
Print the value of sum to the terminal using echo.
Bash Scripting
Need a hint?

Use echo $sum to show the result on the screen.

Try running the script with ./add_numbers.sh 7 8 to see the output 15.