Skip to content
Semillero
ARES

Linux

Bash scripts

By Juan Felipe Martínez Bedoya

A bash script is a file containing commands you would normally type in the terminal. It also lets you create variables, use the arguments the file is run with, and write structures such as conditionals or loops. By convention these files end in .sh.

Every bash script starts with this line:

#!/bin/bash

To run it, give it execute permission (see chmod):

chmod +x myScript.sh
./myScript.sh

Basics

Variables

When creating a variable, write its name without $ and with no spaces around the =. To use it, prefix it with $:

myVariable=3
echo $myVariable

Arguments

The arguments the script is run with are stored in $1, $2, … $n. For example, ./myScript.sh hello puts hello in $1.

Conditionals

if [ condition ]; then
    # code
elif [ condition ]; then
    # code
else
    # code
fi

Printing to the screen

echo "Hello world!"

The .bashrc file

~/.bashrc is a special script that runs every time a new terminal opens. It is usually where environment variables are defined or the ROS environment is loaded. To apply changes without opening another terminal:

source ~/.bashrc

Translated from Spanish.