Manipulate bash variables
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.
For a detailed yet portable guide on bash commands, please refer to Bash_Quick_Reference.pdf
Also browse:
- Mendel Cooper's Advanced Bash-Scripting Guide with example commands at <http://tldp.org/LDP/abs/html/index.html>
- Oreilly's bash in a nutshell: <http://docstore.mik.ua/orelly/linux/lnut/index.htm>
Contents
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.
#! /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
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
...