0
0
Bash Scriptingscripting~5 mins

Command-line arguments ($1, $2, ...) in Bash Scripting

Choose your learning style9 modes available
Introduction

Command-line arguments let you give information to a script when you start it. This helps the script do different things without changing its code.

You want to tell a script which file to process without editing the script.
You need to pass a username or password to a script securely.
You want to run the same script with different options or settings.
You want to automate tasks that require different inputs each time.
You want to make your script flexible and reusable.
Syntax
Bash Scripting
script_name.sh arg1 arg2 arg3 ...

Inside the script:
$1  # first argument
$2  # second argument
$3  # third argument
...
$#  # number of arguments
$@  # all arguments as separate words
$*  # all arguments as a single string

The first argument is accessed with $1, the second with $2, and so on.

$# tells how many arguments were given.

Examples
This script prints the first and second arguments you give it.
Bash Scripting
#!/bin/bash

echo "First argument: $1"
echo "Second argument: $2"
This script checks if you gave at least two arguments and tells you how many you gave.
Bash Scripting
#!/bin/bash

if [ "$#" -lt 2 ]; then
  echo "Please provide at least two arguments."
  exit 1
fi

echo "You gave $# arguments."
This script loops through all arguments and prints each one.
Bash Scripting
#!/bin/bash

for arg in "$@"; do
  echo "Argument: $arg"
done
Sample Program

This script expects exactly two arguments: a name and an age. It then greets the user using those values.

Bash Scripting
#!/bin/bash

# This script greets the user with their name and age

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <name> <age>"
  exit 1
fi

name=$1
age=$2

echo "Hello, $name! You are $age years old."
OutputSuccess
Important Notes

Always check if the right number of arguments is given to avoid errors.

Use quotes around variables like "$1" to handle spaces correctly.

$0 holds the script's name, useful for usage messages.

Summary

Command-line arguments let scripts get input when they start.

Use $1, $2, etc., to access each argument.

Check $# to know how many arguments were given.