Show Menu
Cheatography

BASH Scripting by

Lists and List Options

ls
List all values in present working directory
ls -R
List all files in sub-di­rec­tories as well
ls -a
List hidden files as well

Moving and Renaming Files

mv file "new file path"
Moves the files to the new location
mv filename new_fi­le_name
Renames the file to a new filename

Insert mode

i
insert at cursor
a
Write after cursor
A
Write at end of line
ESC
Terminate insert mode
u
Undo last change
U
undo change to entire last line

For loop

# For loop in Bash; Basic
for x in 1 2 3
do
    echo $x
done
1
2
3

# For loop in Bash; Range
{START..STOP..INCREMENT}
for x in {1..5..2}
do
    echo $x
done
Output:
1
2
5


# For loop; Three expression 
for ((x=2;x<=4;x+=2))
do
    echo $x
done

Output:
2
4
 

Home Directory

cd
Navigate to home directory
cd ..
Move one level up
cd /
Move to root directory

Process Management

ps
Display currently running processes
ps -ef
Display currently running processes on system

Search Files

grep pattern files
grep 'word' filename
grep -i
Case insens­­itive search
grep -R 'httpd'
Look for all files in the current directory and in all of its subdir­ect­ories
grep -c 'nixcraft' frontp­age.md
Search and display the total number of times that the string ‘nixcraft’ appears in a file

Directory with a for loop

# Search for books in the book directory that contain air

for book in $(ls books/ | grep -i 'air')
do
    echo $book
done

AirportBook.txt
FairMarketBook.tx

Case Statements

case 'STRING' in
PATTERN1)
COMMAND1;;
PATTERN2)
COMMAND2;;
*)
DEFAULT COMMAND;;
esac

case $(cat $1) in
sydney)
mv $1 sydney/ ;;
melbourne|brisbane)
rm $1 ;;
canberra)
mv $1 "IMPORTANT_$1" ;;
*)
echo "No cities found" ;;
esac
 

Creating and viewing a file

Creates a new file
cat > filename
Displays the file content
cat filename

BASH variables

Set with an equal sign
greeti­ng=­"­Hel­lo"
Access with a $
echo $greeting

Control Flow

Direct Output of Second command to first
1st_co­mmand $ 2nd Command
Runs the 2nd command only if the 1st command runs succes­sfully.
1stcommand && 2nd Command
Runs the 2nd command only if the 2nd command does not run succes­sfully.
A || B # Run B if and only if A failed

While Statement

Set a condition which is tested at each iteration:

x=1
while [ $x -le 3 ];
do
    echo $x
     ((x+=1))
done

if, then, else statement

if then else:
x="Q­uee­n"
if [ CONDITION ];
if [ $x == "­Kin­g" ];
then # SOME CODE
then echo "$x is a King!"
else # SOME OTHER CODE
else echo "$x is not a King!"
fi
fi

Navigating With Cursor

Alt + b
move backward one word
Alt + f
move forward one word
Alt + u
make entire word after cursor uppercase
Alt + c
make first letter after cursor uppercase
Alt + d
delete word after cursor
^a
beginning of line
^e
end of line
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          More Cheat Sheets by datamansam