Manipulate bash variables

From BITS wiki
Jump to: navigation, search

Bash is the natural language of the terminal on most unix systems (hit has cousins that we will not detail here and are reserved to geeks with very specific expectations). Often, when writing scripts, users need to extract some parts of a file path or define new names for inputs or outputs. Bash has a number of very helpful functions to perform manipulations on variables, some of which are exemplified here.

Not all Bash is taught here but only significant parts used in our scripts.

Cli tools.png For a detailed yet portable guide on bash commands, please refer to Bash_Quick_Reference.pdf

Also browse:

require the presence of argument(s) after the script name

When creating scripts, programers need to get user input that matches the code requirements. It is useless to start a script if the input is absent, therefore an initial test for arguments and verbose-enough comments should always be implemented to prevent aberrant script behaviour and help the end-user.

Handicon.png Exiting a command with 0 means success, exiting with 1 denotes failure

#! /usr/bin/env bash
# 1) exactly one argument is required, else die
if [ $# -ne 1 ]; then
# echo some warning here
exit 1
fi
 
# 2) exactly one argument is present or not
if [ $# == 1 ]; then
# do something here
else
# do something else
fi
 
# 3) if at least one argument is expected
if [ $# -lt 1 ]; then
echo "Usage: ${0##*/} <arg1> < arg2 (opt)> < arg3 (opt)> < arg4 (opt)>"
exit 1
fi
# more code here will be executed if the test passed

Handicon.png bash test blocks need spaces after the opening '[' and before the closing ']'

get a variable value from the user OR use a predefined default value

#! /usr/bin/env bash
# get the number of threads from the first argument '$1' or set it to 4 b y default
# not the absence of $ for '1' inside the '{}'
nproc=${1:-4}
 
# here, another variable is used by default and written with its '$' inside the '{}' block
myvar=${2:-${another-var}}

get the name of the current script

The full path to the current script is stored in the variable '$0'

#! /usr/bin/env bash
# we can extract the end of that path (= script name) by 
# removing all text from the front up to the last '/'
echo "# running: "${0##*/}

more examples will add-up here

#! /usr/bin/env bash
...