Bash (Unix shell)

From David's Wiki
Revision as of 02:59, 26 July 2020 by David (talk | contribs) (→‎Usage)
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)

Bash Scripting


Getting Started

Here is an example bash script

#!/bin/bash
# A simple variable example
myvariable=Hello
anothervar=Fred

echo $myvariable $anothervar

You can check your bash scripts using https://www.shellcheck.net/.

Usage

Basic If Statements

https://linuxize.com/post/bash-if-else-statement/

if [[ $VAR -gt 10 ]] then
  echo "The variable is greater than 10."
elif [[ $VAR -eq 10 ]] then
  echo "The variable is equal to 10."
else
  echo "The variable is less than 10."
fi

Comparisons

  • -eq is ==
  • -gt is >
  • -ge is >=

Check if File/Folder Exists

See https://linuxize.com/post/bash-check-if-file-exists/#check-if-directory-exist.

Arrays

DRIVES=(
  /media/veracrypt1
  /media/veracrypt2
  /media/veracrypt3
  /media/veracrypt4
  /media/veracrypt5
  /media/veracrypt6
  /media/veracrypt7
  /media/veracrypt8
  /media/veracrypt9
)

for i in "${DRIVES[@]}"
do
        ls $i
done
Notes
  • "${DRIVES[@]}" means every element will be a new word
  • "${DRIVES[*]}" will expand the array into a single word

Functions

#!/bin/bash 
function say_hello {
    echo Hello $1
}
say_hello World

dirname

Stack overflow

How to get the source directory of the bash script

#!/bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

.bashrc

Your .bashrc file will be loaded for each terminal.

Presentation of Shell Variable

Add the following to show your

PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$'

Brace Expansion

When you type the following:

echo {red,green,blue}_apple

bash will print out

red_apple green_apple blue_apple

If you want to save this into a variable, you can save it as an array:

APPLES=({red,green,blue}_apple)
echo "${APPLES[@]}"