Duncan Wither

Home Notes Github LinkedIn

Terminal Tut 3 - Scripting

Written: 05-Mar-2022

Bash Script Basics

So here’s some stuff for writing scripts. The language here is bash1 if you’re looking up help on the internet.

Scrips are great because you can write more complex commands easier, but fundamentally all of this can be pasted into the command line, line by line. It’s just not so fun.

Hashbang

The start of your script should (it will probably work without it) start:

#!/bin/bash

This is so the computer knows what language to run.

Then you can start writing the functionality. Functionality is up to you, but here’s some useful bits

for Loop

To loop over files in a directory:

for f in $FILES
do
    # Do something here
    echo "Reading filename: $f"
done

To loop over the lines of a file use (useful if there are spaces in a list of filenames):

while IFS= read -r line
do
    # Doing something on each line
    echo "Text read from file: $line"
done < my_filename.txt

if Statement

if [ expression ]
then
   Statement(s) for true
else
   Statement(s) for false
fi

Check two numbers are equal

[ "$a" -eq "$b" ]

Check two strings are equal

[ "$str1" = "$str2" ]

File Names w/ Spaces

This got me alot as a beginner. Hopefully it won’t get you too much. The main fix was to change the IFS variable by adding the line below to the top of your script.

IFS=$'\n'

I’ve heard it might be hacky, but it works well enough for me.

Function arguments

User Input

There’s many ways to provide for user input. More often than not a basic [y/n] will suffice:

read -r -p "Are you sure? [y/N] " response
case "$response" in
    [yY][eE][sS]|[yY])
        do_something
        ;;
    *)
        do_something_else
        ;;
esac

I’ve also used this tutorial for help. This can progress into other full blown terminal user interfaces, but for simplicity stick to this or basic multiple choice.

find Usage

Very useful for finding files (very surprising). Mainly I use it as an alternative to ls | grep, as shellcheck tells me off for that kind of behaviour.

Basic Usage:

find {dir} {comand}

I like to search by regex, for example, searching for pictures:

find . -iregex '.*\.\(png\|jpg\)'

find in current directory (.) with the regex2 for a file with any name length engin in .jpg or .png3.

Cheat sheet

For all this and more in a condensed format see the Scripting Cheat Sheet.

Previous…

Terminal Tut 2 - Chaining

Next…

Terminal Tut 4 - Regex intro


  1. yes bash not sh (sh is a stricly compliant posix shell see bash vs sh). Just another thing to ignore at the moment.↩︎

  2. Note: -iregex ignores case, -regex doesn’t.↩︎

  3. Note: escaped chars. needed↩︎