Skip to main content
Bash Scripting – Complete Beginner to Advanced Guide
CHAPTER 12 Intermediate

Command-Line Arguments

Updated: May 16, 2026
25 min read

# CHAPTER 12

Command-Line Arguments

1. Introduction

If you write a script named pingserver.sh that relies on the read command to ask the user for an IP address, the script requires a human sitting at the keyboard to press Enter. This destroys the possibility of complete automation. A true DevOps script must be capable of running entirely "headless," receiving its instructions at the exact moment it is launched. When you type ls -la, the -la is a command-line argument passed into the ls program. In this chapter, we will learn how to design our own scripts to accept arguments. We will master Positional Parameters ($1, $2), implement argument validation logic, and utilize special variables ($#) to build robust, professional command-line tools.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Pass external string data into a script at runtime.
  • Capture input data using Positional Parameter variables ($1, $2, etc.).
  • Utilize the $# variable to count the total number of arguments provided.
  • Utilize the $@ variable to process all arguments simultaneously.
  • Write validation logic to safely terminate scripts if arguments are missing.

3. Positional Parameters ($1, $2)

When you execute a script and type words after it, Bash automatically scoops up those words and places them into invisible, pre-named variables called Positional Parameters.
  • $0 = The name of the script itself.
  • $1 = The first word typed after the script.
  • $2 = The second word typed after the script.

Example Script (createuser.sh):

bash
1234567
#!/bin/bash

# We don't use 'read'. We just grab the arguments directly.
USERNAME=$1
DEPARTMENT=$2

echo "Creating account for $USERNAME in the $DEPARTMENT department..."

Execution: You must provide the data at launch:

bash
12
./create_user.sh Alex Engineering
# Output: Creating account for Alex in the Engineering department...

4. Special Argument Variables ($# and $@)

To build robust scripts, you need metadata about the arguments the user provided.

1. Counting Arguments ($#): The $# variable holds a numeric integer representing exactly how many arguments the user provided.

bash
1
echo "You provided $# arguments to this script."

2. All Arguments ($@): If you pass 50 server IP addresses to a script, you don't want to type $1, $2... all the way to $50. The $@ variable holds *every single argument* as a massive array.

bash
12345
#!/bin/bash
for IP in "$@"
do
    echo "Pinging $IP..."
done

5. Argument Validation (Failsafes)

If a script requires an IP address to function ($1), what happens if the user forgets to type it? The script will crash, or worse, execute a command on a blank variable (e.g., rm -rf /$1 becomes rm -rf / and deletes the entire hard drive!). You must validate arguments before doing anything.
bash
1234567891011
#!/bin/bash

# Check if the total number of arguments ($#) is NOT equal to 1
if [ $# -ne 1 ]; then
    echo "ERROR: Invalid usage."
    echo "Usage: ./deploy.sh [TARGET_IP]"
    exit 1  # Abort the script immediately
fi

TARGET_IP=$1
echo "Deploying to $TARGET_IP..."

6. Handling Spaces in Arguments

What if an argument contains a space, like a user's full name? If you type: ./script.sh Alex Smith
  • $1 becomes "Alex"
  • $2 becomes "Smith"
To treat a phrase as a single argument, the user MUST wrap it in quotes at execution: ./script.sh "Alex Smith" Now, $1 captures the entire "Alex Smith" string.

7. Diagrams/Visual Suggestions

*Visual Concept: The Positional Parameter Grid* Draw a terminal prompt displaying: ./deploy.sh 192.168.1.5 production Draw arrows pointing down from each word into corresponding memory boxes:
  • Arrow from ./deploy.sh -> Box labeled $0.
  • Arrow from 192.168.1.5 -> Box labeled $1.
  • Arrow from production -> Box labeled $2.
Beside it, draw a box labeled $# containing the number 2. This clearly maps the relationship between the execution string and the internal Bash variables.

8. Best Practices

  • Implement a "Usage" block: Professional scripts always check for a missing argument and instantly respond with a Usage: string. This mimics the behavior of native Linux tools. If you type ping without an IP, it tells you exactly how to use it. Your scripts must do the same to be user-friendly for other engineers.

9. Common Mistakes

  • Confusing $0 and $1: Beginners often think the first word they type (the script name) is $1. It is not. $0 is always reserved for the script's own filename. The actual data payload begins strictly at $1.

10. Mini Project: The Bulk File Renamer

Let's build a script that takes a file extension and changes it.
  1. 1. nano renamer.sh
  1. 2. Write the code:
bash
123456789101112131415161718192021
#!/bin/bash

# Validation
if [ $# -ne 2 ]; then
    echo "ERROR: Requires exactly two arguments."
    echo "Usage: ./renamer.sh [OLD_EXT] [NEW_EXT]"
    echo "Example: ./renamer.sh txt md"
    exit 1
fi

OLD_EXT=$1
NEW_EXT=$2

# Iterate over all files matching the old extension
for FILE in *.$OLD_EXT
do
    # Use standard bash substitution to rename the string
    NEW_NAME="${FILE%.$OLD_EXT}.$NEW_EXT"
    mv "$FILE" "$NEW_NAME"
    echo "Renamed: $FILE -> $NEW_NAME"
done
  1. 3. chmod +x renamer.sh. This is a fully functional CLI tool!

11. Practice Exercises

  1. 1. Explain the architectural advantage of providing data to a script via Command-Line Arguments ($1) rather than prompting the user via the read command.
  1. 2. Differentiate the operational utility of the $# variable versus the $@ variable.

12. MCQs with Answers

Question 1

An administrator executes the following command: ./backup.sh /var/log /tmp. Inside the backup.sh script, which variable inherently holds the string value /tmp?

Question 2

To prevent a script from executing disastrously with missing variables, an engineer writes a validation block. Which specialized variable is utilized inside the if statement to mathematically verify the user provided exactly two arguments?

# Answer: d) $#

13. Interview Questions

  • Q: A junior DevOps engineer writes an automated server reboot script that accepts a target IP address as $1. The script lacks any validation logic. Explain the specific risk of running this script via an automated pipeline that occasionally fails to generate an IP address variable.
  • Q: Explain the structural behavior of the $@ variable. If a script executes with ./run.sh server1 server2 server3, walk me through exactly how you would parse the $@ variable to ping each server sequentially.
  • Q: A user runs your script using the syntax ./add_user.sh John Doe. Your script utilizes $1 to create the username, but it only creates the user "John". Explain the syntactical mistake the user made during execution, and how they must format the command to pass the full name as a single positional parameter.

14. FAQs

Q: What if I have more than 9 arguments? Can I use $10? A: You can, but you MUST wrap it in curly braces: ${10}. If you just type $10, Bash will interpret it as the variable $1 with a literal zero tagged on the end! However, if you are passing more than 9 arguments, you should probably be using $@ to loop through them anyway.

15. Summary

In Chapter 12, we untethered our scripts from human interaction, enabling true "headless" automation. We harnessed Positional Parameters ($1, $2) to ingest external data streams seamlessly at the moment of execution. We fortified script integrity by leveraging the argument count variable ($#) to enforce strict usage syntax, aborting execution if critical data was omitted. Finally, we utilized the omnibus $@ variable to process massive, indeterminate arrays of arguments, transforming static scripts into dynamic, scalable Command-Line Interfaces (CLIs).

16. Next Chapter Recommendation

Your script is fully autonomous, but you still have to press Enter to start it. To achieve absolute automation, we must hand control of the script over to the Linux timekeeper. Proceed to Chapter 13: Scheduling Tasks with Cron.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·