Table of Contents

Bash

The Bourne Again SHell is common on GNU/Linux systems and it is worth knowing a bit about it as it can be leveraged to great advantage with just a little knowledge.

General Syntax

For loops

snippet.bash
# List the file names
for i in $( ls ); do
     echo item: $i
done
# Loop over range of numbers
for i in `seq 0 9`; do
    echo $1
done

Default Variables

Bash has many default variables, here are some

Variable Description
"${BASH_SOURCE[0]}" The directory from which a script is being called

Parsing Arguments

Arrays

You must declare a variable to be an array, after doing so you can assign items to an array and subsequently access elements by index or loop over them…

snippet.bash
declare -a AN_ARRAY
AN_ARRAY=( element1 element2 element3 element4 element5 )
# Indexing starts at zero
AN_ARRAY[0] 
 
# Loop over elements
for ELEMENT in  "${AN_ARRAY[@]}"; do
    echo $ELEMENT
done

Archiving

Create an archive with the current date (or time if you choose to format it as such) using…

snippet.bash
tar cjvf archive-$(date +"%Y-%m-%d").tar.bz2 *

Script Tricks

Insert date

You can insert a date in-line by using the following with the desired format…

snippet.bash
$(date +"%Y-%m-%d") 
$(date +"%F") # equivalent to above
$(date +"$s") # seconds since epoch
$(date +"%Y-%m-%d-%H:%M:%S")
$(date +"%F-%X") # equivalent to above

Make a directory for every file

Make a directory for every file

You can use variable substitution to quickly make a directory for every file in a given location (from here).

snippet.bash
  cd path/to/directory
  FILE_EXT="txt"
  for x in *.txt; do
    mkdir "${x%\.txt}" && mv "$x" "${x%\.}"
  done

Batch rename files

This is easy if you actually use ZSH rather than Bash courtesy of zmv.

Multi-character arguments

See here

xarg

Options

Small getopts tutorial Bash Hackers Wiki

My scripts

Links