Skip to content

Bash Notes

Terminal window
echo "Hello World with new line"
Terminal window
echo -n "Hello World without new line"
Terminal window
while [ $bool ] do
# ...Code...
done
Terminal window
for (( i = 0; i < 10; i++ )) do
# ...Code...
done
Terminal window
if [ $bool ] ; then
# Do something
elif [ $other_bool ] ; then
# Do something else
else
# Do something else
fi
Terminal window
read a
echo $a

Number of arguments: $#

Nth Argument: $n (n = [1-9])

Terminal window
function name(){
}
Terminal window
file="book.txt"
while read line; do
echo $line
done < $file
Terminal window
for i in [dir]/* ; do
echo "$i"
done
Terminal window
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"
fi
Terminal window
if [ $# -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;
Terminal window
echo "Wait for 5 seconds"
sleep 5
echo "Done"

cut -d [seperation_character] -f[field_num]

Terminal window
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

Terminal window
ls | sort | uniq -c
  • tr [first_set] [second_set]

Replaces the first set of characters with the second one

Terminal window
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

Terminal window
tr -s " "

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

echo [message] 1>&2; exit [num!=0]

Terminal window
if [ $# -ne 1 ] ; then
echo "One argument needed" 1>&2;
exit 1
fi

egrep [options] PATTERN [FILE…]

-v reverse of the pattern

--color adds color to matches

-c count the number of matches

-i ignores case