Bash notes

From raju

Scripts

Check number of arguments

    $cat check_arg_num.sh
    #! /usr/bin/env bash
    set -e
    set -u
    if [ "$#" -ne 1 ]; then
      echo "Usage: $0 foo" >&2
      exit 1
    fi
    foo=$1
    echo $foo
    

Sample run without an argument

    $./check_arg_num.sh
    Usage: ./check_arg_num.sh foo
    

Sample run with an argument

    $./check_arg_num.sh something
    something
    

full name, file name, file head, extension

    for fullname in /path/to/*.csv
    do
    fname="${fullname##*/}"
    fhead="${fname%.*}"
    ext="${fname##*.}"
    echo $fullname $fname $fhead $ext
    done
    

Ref:- https://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash

replace string

    $a="space_kama_raju_kama_raju_kama_raju"
    
    $echo $a
    space_kama_raju_kama_raju_kama_raju
    
    $echo ${a/kama/foo}
    space_foo_raju_kama_raju_kama_raju
    
    
    $echo ${a//kama/foo}
    space_foo_raju_foo_raju_foo_raju
    

looping on the command line

    for i in foo.csv bar.csv; do echo "==>" $i "<=="; cat $i; echo ; done
    

default arguments

The idea here is to have some default values assigned to a variable if nothing is specified on the command line. If some values are specified on the command line, they will be used instead.

    $cat default_args.sh
    #! /usr/bin/env bash
    
    if [ "$#" -eq 0 ]; then
        dirs=(
            "path1"
            "path2"
            )
    else
        dirs="$@"
    fi
    
    for d in ${dirs[@]}
    do
        echo $d
    done
    
    $./default_args.sh
    path1
    path2
    
    $./default_args.sh foo bar
    foo
    bar
    

Used in git_status.sh to get the list of directories on which we want to run "git status" type of commands.

Demonstrates | check number of arguments in a bash script

sort after

ISO-8601 compliant dates

    $ date +%Y-%m-%d
    2017-10-30
    
    $ date +%Y-%m-%dT%H:%M:%S%z
    2017-10-30T17:44:13-0400
    

You can also achieve this by -I

    $ date -I
    2017-10-30
    
    $ date -Iminutes
    2017-10-30T17:47-04:00
    
    $ date -Iseconds
    2017-10-30T17:47:39-04:00
    

Equivalence between -Iseconds and -u

    $date +%FT%T%z
    2017-10-30T17:53:06-0400
    
    $date -u +%FT%TZ
    2017-10-30T21:53:06Z
    

Basically UTC time + offset printed by %z is equal to the local time.

Ref:-

Missing Features

  1. Currently, it is not possible to list files by modification time using tab completion. Use zsh instead.

Ref:- http://lists.gnu.org/archive/html/bug-bash/2014-12/msg00161.html
http://www.zsh.org/mla/users/2015/msg00078.html