Bash Scripts — Part 3 — Command-Line Options and Switches

Mikhail Raevskiy
Introduction into BASH
11 min readJul 28, 2020

--

Having mastered the previous parts of this series, you learned about what bash scripts are, how to write them, how to control the flow of a program, how to work with files. Today we will talk about how to add interactivity to scripts, equipping them with capabilities to receive data from the user and to process this data.

Photo by Fernando Hernandez on Unsplash

The most common way to pass data to scripts is by using command line parameters. By calling the script with parameters, we give it some information with which it can work. It looks like this:

$ ./myscript 10 20

In this example, the script is passed with two arguments — “10” and “20”. All this is good, but how do you read the data in the script?

Reading command line parameters

The bash shell assigns command line parameters entered when invoking the script to special variables called positional parameters:

  • $0- the name of the script.
  • $1- first parameter.
  • $2- the second parameter - and so on, up to the variable $9 that contains the ninth parameter.

Here’s how you can use command line parameters in a script using these variables:

#!/bin/bash
echo $0
echo $1
echo $2
echo $3

--

--

Mikhail Raevskiy
Introduction into BASH

Bioinformatician at Oncobox Inc. (@oncobox). Research Associate