Quick guide to shell scripts in BASH

Starting off

As we want our script to be run by BASH, we need to tell the shell what to run our script with so the first line should be:-

#!/bin/bash

It's possible that BASH on your system may be elsewhere, say, /usr/bin/bash. You can find the BASH in your path with:-

$ which bash
/bin/bash
$

Let's test this with a quick example:-

#!/bin/bash
echo "Hello from your Bash Script."
echo "Your current directory is ${PWD} and your file here are:-"
ls -l 
exit 0

Setting Variables

Variables are set thus, note no space round the = sign:-

MYVAR='Hello'

Quotes are not always required, so MYVAR=Hello is ok, but MYVAR=Hello Friend is not as it contains a space which is treated as an argument delimiter.

It can be read out with $MYVAR but ${MYVAR} is generally better (except inside [ and ] for comparisons).

Single and double quotes are treated differently. Double quotes allow variables to be expanded, single quotes are literal.

GREETING='Hello'
MYVAR1='${GREETING}'   # MYVAR1 will contain ${GREETING}
MYVAR2="${GREETING}"   # MYVAR2 will contain Hello

If your variables could contain spaces, it is better to reference them as “${GREETING}”, not just ${GREETING}. This ensures that once expanded, the variable is not split in to two, eg. it remains as “Hello Friend”

Variable expansion example

A command can be created from combining variable expansion outputs:-

#!/bin/bash
 
COMMAND='ls'
FLAGS='-la'
 
${COMMAND} ${FLAGS} ${HOME}

Running this script actually runs ls -la /home/andrew. COMMAND and FLAG should be understood now, but $HOME is set by your shell as an environment variable. These can be listed with the env command:-

andrew@ubuntu20:~/tmp$ env
SHELL=/bin/bash
PWD=/home/andrew
LOGNAME=andrew
HOME=/home/andrew
LANG=en_GB.UTF-8
...edited...
USER=andrew
DISPLAY=localhost:10.0
PATH=/home/andrew/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
SSH_TTY=/dev/pts/0
_=/usr/bin/env
OLDPWD=/home/andrew/tmp

Some of these are obvious, as you can see HOME is your home directory, PATH is the list in order of where your command interpreter will look for commands to run, PWD and OLDPWD are the current and previous directory you are in, _ is the command and path of the command being run.

Suppose we want to combine and upper case string with a lower case one:-

#!/bin/bash
UPPER='ABCD'
 
echo "$UPPERabcd"

This won't work as expected as BASH thinks the variable we want to expand is “$UPPERabcd” which doesn't exist, but if we use curly braces, we can tell BASH exactly the variable name:-

echo "${UPPER}abcd"

This page has been accessed:-
Today: 1
Yesterday: 1
Until now: 142

 
linux/bash-quickguide.txt · Last modified: 03/01/2024 12:16 by andrew