Bash Cheat Sheet

Released in 1989 Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell and distributed widely.

This is just a small example of common things I use.
A larger example is available at http://cli.learncodethehardway.org/bash_cheat_sheet.pdf

General

Find where bash is installed

which bash

Create a file (end with .sh)

nano example.sh

Top of all files

#!/bin/bash

Make file executable (may need to use sudo)

chmod +x [filename]

Run the script file

./[filename]

Add a comment

#This is a comment

Files

Create file

touch test.txt

Put content in file

echo “test” > test.txt

print contents of file

cat test.txt

Printing Text

print something on screen

echo “some text”

print something without going onto a new line after

echo -n “some text”

print colours

echo -e "\033[0;35m colours here"

Colours will remain during the process until you change the colour again.

echo -e "\033[0;35m colours here \033[1;37m"

Colour options:

Black       0;30     Dark Gray     1;30
Blue        0;34     Light Blue    1;34
Green       0;32     Light Green   1;32
Cyan        0;36     Light Cyan    1;36
Red         0;31     Light Red     1;31
Purple      0;35     Light Purple  1;35
Brown       0;33     Yellow        1;33
Light Gray  0;37     White         1;37

Set variable (no white space)

name=“GlynRob”

print variable

echo $name

Take arguments
i.e. test.txt Hello World

$1 becomes Hello and $2 becomes World

Other options

All arguments       ${@}
Path to m2          ${0}
Parent Path         ${0%/*}
Current file name   ${0##*/}

Inputs

Take input

read somevariable

If/else

if [ $somevariable == 'GlynRob’ ]
then
    echo “Cool Name”
elif [ $somevariable == ‘Chuck Norris’ ]
then
    echo “Great Name”
else
    echo “Bad Name”
fi

Case Statements

case $somevariable in
    “GlynRob”)
        echo “Cool Name” ;;
    “Chuck Norris” )
        echo “Great Name” ;;
esac

Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *