Bash It Out: A Guide to Bash Statement Types

B

Introduction

Bash is a command language interpreter that executes commands read from the standard input or from a file. Also known as the Bourne Again SHell, bash is the default shell on most Linux distributions and macOS.

Bash provides programming constructs that enable you to control the flow of commands like loops and conditionals. This allows you to write shell scripts to automate repetitive tasks.

In this guide, we will cover the common types of bash statements and constructs that enable control flow. Understanding bash statements allows you to effectively write scripts and get the most out of your Linux command line.

Types of Bash Statements

Bash scripts are made up of a series of commands and statements. There are several different types of statements that can be used in a Bash script.

Simple Commands

A simple command is the most basic type of statement. It calls a single program, passing any options and arguments needed by the program. Simple commands look like normal commands you would type at the Bash prompt.

For example:

echo "Hello World" 

This prints the text “Hello World” to the terminal.

Pipelines

A pipeline strings together a series of simple commands, connecting the stdout of one program to the stdin of another. This allows you to pass data through multiple programs and process it in complex ways.

For example:

ls -l | sort -k5

This lists the contents of the current directory, sorts the results by the 5th field (the file size), and passes the sorted output to the next program.

Lists

A list lets you run a sequence of commands as a group. Each command starts on a new line.

For example:

mkdir newdir
cd newdir
touch file.txt

This will create a new directory, change into it, and create a new empty file.

Compound Commands

Compound commands combine other types of commands and statements using control flow constructs like conditionals and loops. This allows you to control the flow of your program. Common compound commands include if statements, for loops, while loops, and case statements.

Simple Commands

Simple commands are the most basic type of statement in Bash. They consist of a command followed by arguments and have the following syntax:

command [argument1] [argument2] ...

For example:

echo Hello World

This prints the text “Hello World” to the terminal.

Some other examples of simple commands:

ls -l /home/user # List files in directory
date # Print current date 
pwd # Print working directory

Simple commands execute a single program and are the building blocks for other statement types in Bash. Arguments modify the behavior of the command. Simple commands allow you to execute Bash’s many builtin commands and external programs available on the system.

Pipelines

Pipelines allow you to connect the standard output of one command to the standard input of another command. This lets you combine multiple simple commands together and pass data between them.

Here is the basic syntax of a pipeline:

command1 | command2

command1 executes first and its output is fed via the pipe | symbol into the input of command2.

Some examples of using pipelines:

  • List files in the current directory and filter the output to only show .txt files: ls | grep .txt
  • Get a list of running processes, sort it, and show only the first 5 results: bash ps aux | sort | head -5
  • Count the number of lines in a file: cat file.txt | wc -l

Pipelines are useful for chaining together commands where you want to take the output of one and pass it as input to another. This allows you to filter and transform data as it moves between multiple steps.

Lists

Lists allow you to run multiple commands sequentially as a group. There are a few ways to group commands in Bash:

Semicolon Separated

You can separate commands with semicolons to execute them sequentially:

cd folder1; ls; cd ../folder2; ls

This will change to folder1, list its contents, change to folder2, and list its contents.

And Operator

The && operator will execute the next command only if the previous command succeeds:

mkdir newfolder && cd newfolder

This will create a new folder called newfolder, and change into it only if the folder was created successfully.

Or Operator

The || operator will execute the next command only if the previous command fails:

rm file || echo "Error removing file"

This will attempt to delete a file, and print an error if the deletion fails.

Parentheses

You can group commands in parentheses to execute them in a subshell:

(cd folder; ls; cd ..)

This will change to a folder, list its contents, then return back to the original working directory after the group executes.

So in summary, Bash provides several ways to group commands and execute them sequentially as a list. This allows you to combine multiple commands for improved workflow.

Compound Commands

Compound commands are statements that contain other commands. There are 4 main types of compound commands in Bash:

if Statements

The if statement allows you to execute different code blocks based on conditions. The basic syntax is:

if [ condition ]; then
  # code to run if condition is true
fi

For example:

if [ $x -gt 10 ]; then
  echo "x is greater than 10"
fi

This will print “x is greater than 10” if the variable x holds a value greater than 10.

for Loops

for loops allow you to iterate over a set of values. The basic syntax is:

for variable in list; do
  # code to run each iteration  
done

For example:

for i in 1 2 3 4 5; do
  echo $i
done

This will print out the numbers 1 through 5.

while Loops

A while loop executes code repeatedly as long as a condition is true. The basic syntax is:

while [ condition ]; do
  # code to run
done

For example:

x=0
while [ $x -lt 10 ]; do
  echo $x
  x=$((x+1)) 
done

This will print the numbers 0 through 9.

case Statements

A case statement allows you to match a string against multiple patterns and execute code based on the first match. The basic syntax is:

case $variable in
  pattern1)
    # code to run if pattern1 matches
    ;;
  pattern2)
    # code to run if pattern2 matches 
    ;;
esac

For example:

read -p "Enter Y or N: " ans
case $ans in
  Y|y)
    echo "You entered yes"
    ;;
  N|n)  
    echo "You entered no"
    ;;
esac

This prints a message based on whether the user enters y/Y or n/N.

The case statement is useful for handling multiple conditions compactly.

if Statements

The if statement in Bash allows you to execute code blocks conditionally based on the result of a test. The basic syntax is:

if [ condition ] 
then
  commands
fi

The condition inside the brackets is a test that returns true or false. Common tests include:

  • File tests like -d FILE to check if a file exists
  • String comparisons like [ "$A" = "$B" ] to compare strings
  • Numeric comparisons like [ $1 -gt 10 ] to compare numbers

Some examples of using if statements:

# Check if file exists
if [ -f "/path/to/file" ] 
then
  echo "File found"
fi

# Compare strings 
if [ "$NAME" = "John" ]
then
  echo "Name is John"
fi

# Test integer values
if [ $1 -gt 10 ] 
then
  echo "Input is greater than 10"
fi

The if statement allows you to branch your code and only execute certain parts based on the result of the test condition. This is useful for handling different situations and cases in a Bash script.

ing on whether they entered yes or no. If any other character is entered, it will print “Invalid input”.

The case statement is useful for checking multiple conditions and taking different actions depending on the results. It can replace long chains of if/else statements and makes the code more readable.

Add Comment

Recent Posts

Pages

Archives

About

middle aged linux nerd. likes coding and pizza. owner of this particular site.