Bash Notes
echo "Hello World with new line"echo -n "Hello World without new line"while [ $bool ] do
# ...Code...
donefor (( i = 0; i < 10; i++ )) do
# ...Code...
doneif [ $bool ] ; then # Do somethingelif [ $other_bool ] ; then # Do something elseelse # Do something elsefiTake input
Section titled “Take input”read aecho $aArguments
Section titled “Arguments”Number of arguments: $#
Nth Argument: $n (n = [1-9])
Functions
Section titled “Functions”function name(){
}Read a file
Section titled “Read a file”file="book.txt"
while read line; do echo $linedone < $fileRead a directory
Section titled “Read a directory”for i in [dir]/* ; do echo "$i"doneif tests
Section titled “if tests”arg = $1
if [ -e $arg ] ; then echo "$arg exists"fi
if [ -f $arg ] ; then echo "$arg is a file"elif [ -d $arg ] ; then echo "$arg is a directory"else echo "$arg is something else"fiif [ $# -ne 1 ] ; then echo "I need only one argument" 1>&2 exit 1;fi
if [ ! -f $1 ] ; then echo "Argument is not a file" 1>&2 exit 2;echo "Wait for 5 seconds"sleep 5echo "Done"cut -d [seperation_character] -f[field_num]
cut -d " " -f1- [expression] | sort -k[num] -t [char]
Sort the lines of the output of the [expression] based on the [num] field after sererating them based on the [char]
Before uniq always sort
Removes concurrent duplicate lines
-c adds a prefix of the number of occurences
ls | sort | uniq -c- tr [first_set] [second_set]
Replaces the first set of characters with the second one
tr [:lower:] [:upper:]- tr -s [character]
Replace each sequence of a repeated character that is listed in the last specified SET, with a single occurrence of that character
tr -s " "Inline code
Section titled “Inline code”a=[command]
The result of the [command] goes into the variable a
[expression] | head -n[num]
Print the first [num] of lines of the [expression]‘s output
[expression] | tail -n[num]
Print the last [num] of lines of the [expression]‘s output
Error message
Section titled “Error message”echo [message] 1>&2; exit [num!=0]
if [ $# -ne 1 ] ; then echo "One argument needed" 1>&2; exit 1fiegrep [options] PATTERN [FILE…]
Options
Section titled “Options”-v reverse of the pattern
--color adds color to matches
-c count the number of matches
-i ignores case