Sunday 28 August 2016

Bash scripts cheat sheet



Bash is:
  • Unix shell (command-line interpreter, command processor). It can process commands that user types in text window (terminal) or commands written in a file (shell script).
  • command language 
This article contains some my notes about writing shell scripts.

Here are some useful utility functions (source):


yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
asuser() { sudo su - "$1" -c "${*:2}"; }


  • yell: print the script name and all arguments to stderr
    • $0 is the path to the script
    • $* are all arguments
    • >&2 means > redirect stdout to & pipe 2. pipe 1 would be stdout itself.
  • die does the same as yell, but exits with a non-0 exit status, which means “fail”.
  • try uses the || (boolean OR), which only evaluates the right side if the left one failed.
  • $@ is all arguments again, but different.



set -e 

At the top of the script this will cause it to exit upon any command which errors.

 

set -x

Setting the -x tells Bash to print out the statements as they are being executed. It can be very useful as a logging facility and for debugging when you need to know which statements were execute and in what order. [from Bash set -x to print statements as they are executed]

It is possible to combine two above commands into a single one:

set -ex

Getting the current directory:


$ pwd


To find some executable:


$ where perl
C:\cygwin64\bin\perl.exe



$ which perl
/usr/bin/perl


Viewing the whole content of the file:


$ cat /bin/man2html


Viewing only the first line of the file:

$ head -n 1 file.txt


Viewing only the last line of the file:

$ tail -n 1 file.txt


Editing file:

$ vi /bin/man2html


Initially, vi opens in command mode.

i - to enter edit (insert) mode
ESC - to exit edit mode
:wq - write and quit
:q! - quit without saving changes


Logging



It is a good practice to create a log file for each command/process/script/application that we run. We append both stdout and stderr into file:

my_command >> /tmp/my_command.log 2>&1


----
 

Resources:

 

No comments: