Skip to main content

Bash Script Command Line Arguments

Command line arguments in Bash scripts can elevate your scripting skills to the next level. Ever wondered how your favorite Linux commands accept those nifty options and parameters? Believe it or not, it's simpler than you think to replicate this functionality in your own scripts. Let's explore how you can make your Bash scripts as dynamic and user-friendly as you need them to be.

Understanding Command Line Arguments

Command line arguments are parameters you provide to your script at runtime. In Bash scripting, these arguments are handled using special variables. If you've ever used bash script.sh arg1 arg2, then you've already interacted with command line arguments! But what does it mean for your script? Let's break it down.

Special Variables in Bash

In Bash, command line arguments are referenced using special variables:

  • $0: Contains the name of the script.
  • $1, $2, $3, etc.: These hold the values of the first, second, third, and other subsequent arguments.
  • $#: Displays the number of arguments supplied to a script.
  • $*: Represents all the arguments as a single string.
  • $@: Similar to $*, but treats each argument as a separate string.

For instance, if your script is run as bash myscript.sh one two three, $1 would be one, $2 would be two, and so on.

Why Are These Important?

Knowing how to handle command line arguments allows you to make scripts reusable and flexible. Instead of hardcoding values, your script can adapt to input dynamically, making them powerful tools in any developer's toolkit.

Working with Command Line Arguments: A Practical Approach

Let's see these concepts in action with a practical example.

Example: A Simple Script with Arguments

Imagine you want a script that greets a user by their name and age. Here's how you might do it:

#!/bin/bash

# Check if exactly two arguments are provided
if [ $# -ne 2 ]; then
  echo "Usage: $0 <name> <age>"
  exit 1
fi

# Assign arguments to variables
NAME=$1
AGE=$2

# Print a greeting
echo "Hello, $NAME! You are $AGE years old."

Line-by-Line Explanation:

  • #!/bin/bash: Indicates the script should run in the Bash shell.
  • if [ $# -ne 2 ]; then: Checks if the number of arguments is not equal to 2.
  • echo "Usage: $0 <name> <age>": Informs the user how to correctly run the script.
  • exit 1: Exits the script if improper arguments are supplied.
  • NAME=$1 and AGE=$2: Assigns the first and second arguments to variables.
  • echo "Hello, $NAME! You are $AGE years old.": Outputs a personalized greeting.

Enhancing Script Functionality

Expand your script's capabilities with additional options:

#!/bin/bash

while getopts "n:a:h" option; do
  case $option in
    n) NAME=$OPTARG;;
    a) AGE=$OPTARG;;
    h) echo "Usage: $0 -n <name> -a <age>"
       exit 0;;
    *) echo "Invalid option. Use -h for help."
       exit 1;;
  esac
done

if [ -z "$NAME" ] || [ -z "$AGE" ]; then
  echo "Both name and age are required. Use -h for help."
  exit 1
fi

echo "Hello, $NAME! You are $AGE years old."

Line-by-Line Explanation:

  • getopts "n:a:h": Parses command-line options for -n, -a, and -h.
  • case $option in ...): Handles each option, using OPTARG for argument value.
  • -z "$NAME": Checks if variables are unset or empty.
  • echo "Invalid option. Use -h for help.": Offers help if invalid options are used.

Mastering command line arguments in Bash scripts gives you the freedom to craft versatile and robust scripts. Whether you're automating tasks or creating utilities, handling arguments efficiently can make your scripts far more adaptable and user-friendly.

Curious about related topics? Dive into Shell Scripting Basics for more insights into scripting and automation. Keep exploring, and happy scripting!

Popular posts from this blog

C++ vcpkg Manifest Mode + CMake

 If you've ever tried to install a C++ library and felt like you were assembling furniture without instructions, this article is for you. We're going to talk about vcpkg manifest mode and how it works with CMake , and I'm going to explain it like you're five years old (in a good way — no judgment here). First, Let's Talk About the Problem In most programming languages, adding a library is easy. Python has pip install requests . JavaScript has npm install express . You type one command, and boom, the library shows up in your project. C++ never really had that. For decades, if you wanted to use a library like fmt or nlohmann/json , you had to: Download the source code yourself Figure out how to compile it Tell your compiler where to find the headers Tell your linker where to find the compiled binaries Cry a little vcpkg is Microsoft's answer to this mess. It's a package manager for C++ — like pip or npm , but for C++ libraries. And manifest mode...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...