Skip to content
paSHA3 edited this page Oct 10, 2020 · 33 revisions

Useful Guide for Bash Scripting

Creating bash file:

touch bashfile.sh

To execute bash file run it like this:

./bashfile.sh

Note: Since ".sh" files are sensitive that's why their permission is off by default.

To give it permission write:

chmod +x bashfile.sh

edit your "bashfile.sh" by using gedit and write: echo "Hello World" then execute it...

Note: gedit is not already install, To install it write apt-get install gedit

Linux Terminal Commands run on bash,Try writing "ls" in bashfile.sh and execute it:

If you want to rewrite last command type !!

Copy file in bash:

cp bashfile.sh ~/Desktop

#Copy this file to desktop

Comment's in Bash Sometimes we want to write notes in the file but don't want to show or execute it, For that we use comments:

Single-Line Comments: #This is single-line comment

Multiline Comments:

<<COMMENT

  These are
  multi-line 
  comments 

COMMENT

To check current directory type pwd

Reading file

First, create a text file

Then write something in it

Now to read the file you can use:

cat textfile.txt

To display few lines (Such as first two) you can use: head -n 2 textfile.txt

where -n is the number of line from the top

Same as that if you want to view last 2 lines you can use: tail -n 2 textfile.txt

where -n is number of line (from the last)

To declare variable in bash use myvar=hello

Remember no gaps between it and to call variable type dollar sign before variable and echo it: echo $myvar

Aliases

alias is a shortcut to reference a command. It can be used to avoid typing long commands So instead of writing this: ls -l -a -h -t You can write this: alias lsss="ls -l -a -h -t" and use it like this: lsss To remove alias you can use this: unalias lsss

To check all alias use command "printenv"

Change Prompt

You can change prompt setting by using:

export PS1="\ncommand here> "

You can also use color in prompt:

export PS1="\e[1;31m\nCODE: \e[39m"

Setting won't be same forever it will change to default as you close the terminal to make them permanent change ".bashrc"

Note: Don't edit anything unless you know what you are doing

I have edit my .bashrc and add the path of my art:

Now whenever i open my terminal it will show the art:

Download file using command line:

wget \

http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso

You call also use curl for this:

curl \

http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso \

--output ubuntu.iso

Did you notice you can give multi line command by using \ at the end You should try:

Create tar file:

tar -cf ziped-file.tar myfile

Unzip tar file:

tar -xf ziped-file.tar

Redirection:

Consider there is a long file you want to read by scrolling by using pipe "|" you can do this:

cat textfile.txt | more

Note: Press Enter to scroll...

Redirect output on specific file:

cat textfile1.txt > textfile2.txt

Using this command you are overwriting textfile1.txt into textfile2.txt

If you don't want to overwrite the file you can copy text with:

cat textfile1.txt >> textfile2.txt

To print in new line use /n:

printf "1\n2\n3\n"

Sorting in printf:

sort <(printf "5\n3\n2")

Try using this and guess how it work's:

printf "Salam %s, I'm %s" Ali Umer

Redirection with error doesn't work

python hello.py > a.txt

Can't Redirect Log: To solve this problem you can use this:

python hello.py 2> error.log

Array:

car=('BMW' 'Toyota' 'Honda')

car[2]='Hello' #Declare

unset car[2] #Remove car second value

echo "${car[@]}" #Display all car value

echo "${car[0]}" #Display car first value

echo "${car[1]}" #Display car second value

echo "${car[2]}" #Display car third value

echo "${!car[@]}" #Value of Index (Format 1)

echo "${#car[@]}" #Value of Index (Format 2)

Function's:

function funcName()

{

echo "Hello"

}

funcName

You can also try:

function funcCheck()

{

rv="Salam"

echo "$rv"

}

funcCheck

Conditional Statement:

count=10 #Declare Variable

if [ $count -eq 10 ] #Give Condition

then #If its true

echo "Condition is true"

else

echo "Condition is False"

fi

Try using -ne:

count=10 #Declare Variable

if [ $count -ne 10 ] #Give Condition ne stands for "Not Equals"

then #If its true

echo "Condition is true"

else

echo "Condition is False"

fi

You can also use < and > sign:

count=10 #Declare Variable

if (( $count > 10 )) #Give Condition ne stands for "Not Equals"

then #If its true

echo "Condition is true"

else

echo "Condition is False"

fi

Elif command:

count=10 #Declare Variable

if (( $count > 10 )) #Give Condition ne stands for "Not Equals"

then #If its true

echo "Condition is true"

elif (( $count > 5))

then

echo "Hello Bird !!!"

else

echo "Condition is False"

fi

And Operator:

age=5 #Declare Variable

if [ "$age" -gt 18 ] && [ "$age" -lt 40 ]

then

echo "Welcome"

else

echo "Noooo"

fi

OR Operator:

age=5 #Declare Variable

if [ "$age" -gt 18 -o "$age" -lt 40 ] #You can also use || instead of -o

then

echo "Welcome"

else

echo "Noooo"

fi

for loop:

for i in 1 2 3 4 5

do

echo $i

done

Try also using:

one=Hello

two=My

three=Name

four=is

five=1337

for i in $one $two $three $four $five

do

echo $i

done

for loop (Count)

for i in {1..20} #Print from 1 to 20

do

echo $i

done

for i in {a..z} #Print from a to z (Lower Case)

do

echo $i

done

for i in {A..Z} #Print from A to Z (Upper Case)

do

echo $i

done

#Another thing you can do:

for i in {0..20..2} # count from 0 to 20 with the gap of 2

do

echo $i

done

standardize way to write for loop in bash:

for (( i=0; i<5; i++ ))

do

echo $i

done

i=0 is basic declaration

i<5 is a condition where it will stop

i++ is a action on per step

A file reading script:

echo "Enter File to Create"

read filename #Ask for a file to take as input

if -f "$filename" # The -f will check that either file exist or not...

then

echo "Text to Append" #Take user file to put in text...

read filetext

echo "$filetext" >> $filename #Redirect text in file

else

echo "$filename don't exist" #If file doesn't exist

fi

You can also make script like this:

echo "Enter File to read"

read filename

if -f "$filename"

then

  rm $filename
  echo "File Deleted !!!"

else

  echo "$filename don't exist"

fi

On conditional statement you can use these condition's:

-e FILE Exists

-r FILE Readable

-h FILE Symlink

-d FILE Directory

-w FILE Writable

-s FILE Size is > 0 bytes

-f FILE File

-x FILE Executable

FILE1 -nt FILE2 1 is more recent than 2

FILE1 -ot FILE2 2 is more recent than 1

FILE1 -ef FILE2 Same files

-z STRING Empty string

-n STRING Not empty string

STRING == STRING Equal

STRING != STRING Not Equal

NUM -eq NUM Equal

NUM -ne NUM Not equal

NUM -lt NUM Less than

NUM -le NUM Less than or equal

NUM -gt NUM Greater than

NUM -ge NUM Greater than or equal

STRING =~ STRING Regexp

(( NUM < NUM )) Numeric conditions

-o noclobber If OPTIONNAME is enabled

! EXPR Not

X && Y And

X || Y Or

Some math:

See the picture:

Another Way:

n1=4

n2=20

echo $(($n1 + $n2 ))

echo $(( $n1 + $n2 ))

echo $(( $n1 * $n2 ))

echo $(( $n1 / $n2 ))

echo $(( $n1 % $n2 ))

Taking user input with script: See the image

To check your current privilege use:

whoami

To check all users:

cat /etc/passwd

To add new user:

sudo useradd syedumerqadri

To remove any user:

sudo userdel syedumerqadri

Note: "cat /etc/passwd | grep syedumerqadri" is used to check specific user

To check all groups use command:

cat /etc/group

To add a new group:

groupadd mygroup

To delete any group:

groupdel mygroup

Permission:

chmod -x myfile.txt #To remove permission

chmod +x myfile.txt #To give permission

Color's cheat sheet:

https://misc.flogisoft.com/bash/tip_colors_and_formatting

For random number use:

$((RANDOM%=200)) # Random number from 0 to 200

Another way to apply math:

a=50 echo $((a + 200))

Replace first occurrence of to in most recent command:

!!:s/<FROM>/<TO>/

To check your command history use:

history

Globe Cheat Sheet: Globe is just simply wildcard !!!

ls hel #List all elements contain words "hel"

ls .*hello #To view hidden file (You can also use "ls *hello")

ls hello.*g?? # ? can be any word

ls ???? #List all with 4 word

ls hello.*g[ab] # last can be either hello.aga or hello.agb

ls report-200[1-9].txt #To list reports from 2001 to 2009

echo [A-Z]*berry.??? #To find

echo [ABCDEFG]*berry.??? #To find

Disable recursive file creation:

set -o noclobber

( It will avoid overlay files (echo "hi" > foo) Give error when creating a file which already exist)

Dictionary Cheat Sheet

declare -A sounds

sounds[dog]="bark"

sounds[cow]="moo"

sounds[bird]="tweet"

sounds[wolf]="howl"

echo ${sounds[dog]} # Dog's sound

echo ${sounds[@]} # All values

echo ${!sounds[@]} # All keys

echo ${#sounds[@]} # Number of elements

unset sounds[dog] # Delete dog

for val in "${sounds[@]}"; do

echo $val

done

for key in "${!sounds[@]}"; do

echo $key

done

Change case of Variable:

STR="HELLO WORLD!"

echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)

echo ${STR,,} #=> "hello world!" (all lowercase)

STR="hello world!"

echo ${STR^} #=> "Hello world!" (uppercase 1st letter)

echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)

Parameter Expansion:

name="Umer"

echo ${name}

echo ${name/U/u}    #=> "umer" (substitution)

echo ${name:0:2}   #=> "Um" (slicing)

echo ${name::2}     #=> "Um" (slicing)

echo ${name::-1}    #=> "Ume" (slicing)

echo ${name:(-1)}   #=> "r" (slicing from right)

echo ${name:(-2):1} #=> "e" (slicing from right)

echo ${food:-Cake}  #=> $food or "Cake"

STR="Hello world"

echo ${STR:6:5}   # "world"

echo ${STR:-5:5}  # "world"

${#FOO} #To find length

Brace Expansion:

echo {A,B}.js

echo {1..5}

echo {a..z}

Some CLI Gadget's:

cal #calender

date #date

bc #calculator

Open specific directory in GUI:

xdg-open

To check who is logged in use:

who

w (w is a more detailed who, showing who’s logged in)

Some text processing:

uniq file.txt   #To remove repeating  and just display one

sort file.txt #Sort

diff a b	# diff will report which lines differ between two files

cmp a b  	#reports which bytes differ between two files

Note: grep,awk and sed is detail topic i will cover it in future

if you want to find a documentation of specific command use:

man

For example:

Clone this wiki locally