CLI

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Do Khang Bash command------------------------------------------ Bash

script
Ctrl + Zoom in
Ctrl - Zoom out
Tab Auto-complete
↑ Get the previous commands
↓ Get the following commands
Ctrl L Clear the screen
Ctrl C Cancle a running process
.bashrc The configuration file
 nano .bashrc Edit the aliases part to create new shortcuts

o alias a='printf Hi' ‘a’ is now shortcut for 'printf Hi'


o Need to re-open Ubuntu to apply the change

--------------------------------
pwd Print current directory (Home directory is abbreviated as
~)
cd Go to the Home directory
 Dire to the Dire directory
 ~ to the Home directory
 - to the previous directory
clear Clear the screen
ls List the content of the current directory
 -a All the content (including hidden files)
 -l Long format (File permissions, size, date, ownership…)
 -h Human readable numbers
chmod M Foo Change the mode M of the file Foo
 +x Provide execution permissions
man com Open the manual page for the com command
 e To scroll down
 y To scroll up
Do Khang Bash command------------------------------------------ Bash
script
touch Foo Create an empty file named Foo
nano Foo (Create and) Edit a file named Foo
 Ctrl X To exit
 y “Yes” to save
 Enter To leave the file
cat Foo Show the content of the Foo file, start at the end of the
file
less Foo Show the content of the Foo file, start at the beginning
of the file
 Enter To scroll down line by line
 q To quit
head -n N Foo Show the content of the first N lines in the Foo file
 without -n 10 by default
tail -n N Foo Show the content of the last N lines in the Foo file
 without -n 10 by default
grep string Foo Print out every line containing string in the Foo file
mkdir Dire Create a new directory named Dire
mv Foo Dire Move the file Foo into the Dire directory
cp Foo Dire Copy the file Foo into the Dire directory
rm Dire/Foo Remove the file Foo in the Dire directory
rmdir Dire Remove the empty directory Dire
rm -rf Dire Remove (recursively and forcefully) the non-empty
directory Dire
which com Locate the binary of the command com
whereis com Locate the binary, source, and manual page files of the
command com
locate key List all the directories that have key as part of their
names
x = val Assign val to the variable name x
declare -a arr Declare an array named arr
 arr = ( val1 val2 val3) Assign val1, val2 and val3 into the array arr
 ( ‘a b’ ‘c d’ ) 2 elements ‘a b’ and ‘c d’
 ( ‘a b’ c d ) 3 elements ‘a b’, ‘c’ and ‘d’
Do Khang Bash command------------------------------------------ Bash
script
 arr[n] = val Assign val to the (n-1)th element of the
array arr
declare -i x Declare an integer named x
$ To access
 ? A default variable storing the exit code of the
previous
command
o 0 Successful execution
o 1-255 Failed execution of different types
 x The variable x
 (com) The output of the command com
 ((exp)) The result of the expression exp
 [exp] The result of the expression exp
read Read the user input and assign it into the default build-
in
variable $REPLY
 read x Store the input into the variable x
 read -a arr Store the input into the array named arr
 read -p mes x Prompt the message mes and store the input into x
echo string Print out string
 -e Enable interpretation of escape sequence
printf string Print out string with enabled interpretation of escape
sequence
sed s/old/new/g Replace every old characters with new characters
 sed s/a/d/g Replace every ‘a’ with ‘d’
 sed s/[abc]/d/g Replace every ‘a’,’b’,’c’ with ‘d’
| Pipe the output of one command into another command
 ls | sed “s/a/d/g” List out the content of the current
directory
then replace every ‘a’ with ‘d’
 ls | sed “s/a/d/g” | grep a List out the content of the current
directory
then replace every ‘a’ with ‘d’, then
print
only those lines containing ‘a’
./Foo.sh Execute the Foo.sh shell file
 chmod +x Foo.sh Give permission to execute the Foo.sh shell file
Do Khang Bash command------------------------------------------ Bash
script
history Display every command in the history shell
!N Execute the Nth command in the history shell
!! Execute the very last command in the history shell
 !60 | !! Execute the 60th command then pipe the output into the
very
last command
com1 && com2 Execute command com1 and then execute command com2
htop Display every running process
 ↓↑ To hover between processes
 F9 To kill the chosen process
o Enter at 15 SIGTERM To complete the killing
 F10 To quit
ping web send ICMP ECHO_REQUEST to the web hosts
 ping google.com Can be used to check internet connection
cal Display the calendar
date Display the current date and time
bc Open the calculator
 quit To exit
# Comment
function fun Declare a function name fun
 {
 Function definition goes here
 }
 fun Calling the function by its name
select x in op1 op2 op3
Prompt the user to make a selection, storing either op1,
op2 or op3 into x
 do
 Your commands go here, using x
 break Otherwise endless loop
 done
-b Foo Block special file Foo
-d Dire Return true if directory Dire exists
-e Foo Return true if file Foo exists
Do Khang Bash command------------------------------------------ Bash
script
-f Foo Return true if regular file Foo exists, not a directory
-G Foo Return true if file Foo exists and owned by effective
group ID
-g Foo Return true if file Foo exists and is set-group-id
-O Foo Return true if file Foo exists and owned by effective user
ID
-r Foo Return true if file Foo is readable
-S Foo Return true if file Foo is socket
-s Foo Return true if file Foo is non-zero size
-u Foo Return true if file Foo set-ser-id bit is set
-w Foo Return true if file Foo is writable
-x Foo Return true if file Foo is executable
! Negate the truth value
 ! -x Foo Return false if file Foo is executable
----------------------------------
Arithmetic comparison
 -eq equal
 -ne not equal
 -gt greater than
 -lt less than
 -ge greater than or equal
 -le less then or equal
String comparison
 = equal
 != not equal
 \< less than
 \> greater than
 -z string Return true if string is empty
 -n string Return true if string is not empty
Arithmetic operations
 + addition
 - subtraction
 * multiplication
 / division
 % modulus
 ** power
Do Khang Bash command------------------------------------------ Bash
script
 x=y#z zy = x10
Arithmetic expansion
 $(( expression ))
 $[ expression ]
----------------------------------

1. Global and local variables

# Define bash global variable


# This variable is global and can be used anywhere in this bash script
VAR="global variable"

function bash
{
# Define bash local variable
# This variable is local to bash function only
local VAR="local variable"
echo $VAR
}

echo $VAR
bash
# Note the bash global variable did not change
# "local" is bash reserved word
echo $VAR

The result will


global be:
variable
local variable
global variable

Without
globalthevariable
key word local, we would refer to the global VAR and change its content, hence the result:
local variable
local variable
Do Khang Bash command------------------------------------------ Bash
script

2. Passing arguments
a) Into files

#!/bin/bash
# use predefined variables to access passed arguments
echo $1 $2 $3 ' -> echo $1 $2 $3'

# We can also store arguments from bash command line in special array
args=("$@")
echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]}
${args[1]} ${args[2]}'

#use $@ to print out all arguments at once


echo $@ ' -> echo $@'

# use $# variable to print out number of arguments passed to the bash


script
echo Number of arguments passed: $# ' -> echo Number of arguments
passed: $#'

The result
Bash will be:
Scripting Tutorial
-> echo $1 $2 $3
Bash Scripting Tutorial -> args=("$@"); echo ${args[0]} ${args[1]} $
{args[2]}
Bash Scripting Tutorial -> echo $@
Number of arguments passed: 3 -> echo Number of arguments passed: $#

The
-> 3echo
passed$1
arguments
$2 $3 by default are $1, $2 and $3. In case we change echo $1 $2 $3 into
echo
Bash$a $b $c, theTutorial
Scripting result would be:
-> args=("$@"); echo ${args[0]} ${args[1]} $
{args[2]}
Bash Scripting Tutorial -> echo $@
Number of arguments passed: 3 -> echo Number of arguments passed: $#

$a $b $c are not defined, so they will be empty.

b) Into functions
Do Khang Bash command------------------------------------------ Bash
script
Similarly to passing arguments into files, the arguments passed into functions by default are $1, $2,
$3… However, the arguments are local to their functions, meaning that we always start with $1, $2,
$3… for every function.

#!/bin/bash
function A {
echo I have $1 apples, and I ate $2 of them
}
function B {
echo I have $1 bananas
}
A 3 2
B "4"

The result will


I have be:
3 apples, and I ate 2 of them
I have 4 bananas

3. Bash Trap command

#!/bin/bash
# bash trap command, which sets up a trap to catch the INT (interrupt)
signal, # typically generated by pressing Ctrl+C.
# When this signal is caught, the bashtrap function will be executed.
trap bashtrap INT
# bash clear screen command
clear;
# bash trap function is executed when CTRL-C is pressed:
# bash prints message => Executing bash trap subrutine !
bashtrap()
{
echo "CTRL+C Detected !...executing bash trap !"
}
# for loop from 1/10 to 10/10
for a in `seq 1 10`; do
echo "$a/10 to Exit."
sleep 1;
done
echo "Exit Bash Trap Example!!!"
Do Khang Bash command------------------------------------------ Bash
script
In1/10
the output below you can see that we try to Ctrl + C two times but the script continues to execute:
to Exit.
2/10 to Exit.
^CCTRL+C Detected !...executing bash trap !
3/10 to Exit.
4/10 to Exit.
5/10 to Exit.
6/10 to Exit.
7/10 to Exit.
^CCTRL+C Detected !...executing bash trap !
8/10 to Exit.
9/10 to Exit.
10/10 to Exit.
Exit Bash Trap Example!!!

4. Conditional statement
a) if-elif-else
Here is a simple if-else statement that check to see if a directory exists or not. The program is stored
in the f.sh shell file:

#!/bin/bash
directory="./BashScripting"

# bash check if directory exists


if [ -d $directory ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fi

The spaces within the [ ] is compulsory. Without them, it won’t work. The result will be:
$ ./f.sh
Directory does not exist
$ mkdir BashScripting
$ ./f.sh
Directory exists

Before, there is no directory named BashScripting, the else statement is executed. After we create
one, the condition now turns true, the if statement is executed.
Here is a program containing if-elif-else statements:
Do Khang Bash command------------------------------------------ Bash
script
#!/bin/bash

echo "Enter a number:"


read number

if [ $number -gt 0 ]; then


echo "The number is positive."
elif [ $number -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi

The resultawill
Enter be:
number:
5
The number is positive.

Here is a program containing nested if-else statements:

#!/bin/bash

echo "Enter your age:"


read age

if [ $age -ge 18 ]; then


echo "You are an adult."
if [ $age -ge 21 ]; then
echo "You are old enough to drink."
else
echo "You are not old enough to drink."
fi
else
echo "You are a minor."
fi

The resultyour
Enter will be:
age:
25
You are an adult.
You are old enough to drink.
Do Khang Bash command------------------------------------------ Bash
script
b) case
Unlike an if statement can get lengthy very quickly if you have more than a few possibilities to account
for, the case statement makes it easy to have many different possibilities:

#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2) perl"
echo "3) python"
echo "4) c++"
read choice;
#simple case bash structure
case $choice in
1) echo "You selected bash";;
2) echo "You selected perl";;
3) echo "You selected python";;
4) echo "You selected c++";;
esac

The result
What iswill
yourbe: preferred programming / scripting language
1) bash
2) perl
3) phyton
4) c++
5) I do not know !
3
You selected python

5. Looping
a) for loop
This for loop will list every file or directory it finds inside the Home directory:

for f in $( ls ~ ); do echo $f; done

The result will be:


BashScripting
f.sh
hello_asm_dump
hello_hex_dump
Do Khang Bash command------------------------------------------ Bash
script
This for loop will round a floating point number to its nearest integer:

#!/bin/bash

floating_point_number=3.3446
echo $floating_point_number
# round floating point number with bash
for bash_rounded_number in $(printf %.0f $floating_point_number); do
echo "Rounded number with bash:" $bash_rounded_number
done

The result will be:


3.3446
Rounded number with bash: 3

b) while loop
This while loop will continue to loop until our variable reaches a value of 0 or less.

#!/bin/bash
COUNT=6
# bash while loop
while [ $COUNT -gt 0 ]; do
echo Value of count is: $COUNT
let COUNT=COUNT-1
done

The resultof
Value willcount
be: is: 6
Value of count is: 5
Value of count is: 4
Value of count is: 3
Value of count is: 2
Value of count is: 1

c) until loop
The until works similarly to while, but run with the false condition statement.

#!/bin/bash
COUNT=6
# bash while loop
while [ $COUNT -gt 0 ]; do
echo Value of count is: $COUNT
let COUNT=COUNT-1
done
Do Khang Bash command------------------------------------------ Bash
script
The resultof
Value willcount
be: is: 0
Value of count is: 1
Value of count is: 2
Value of count is: 3
Value of count is: 4
Value of count is: 5

This program uses a for loop to ask user to enter an integer n, check the validation of n, then input n
strings and store them into the arr array:

#!/bin/bash

# Prompt user to input a number


read -p "Enter the number of strings you want to input: " n

# Validate if input is a positive integer


if ! [[ $n =~ ^[1-9][0-9]*$ ]]; then
echo "Error: Please enter a valid positive integer."
exit 1
fi

# Declare an array to store strings


declare -a arr

# Loop to input n strings


for (( i=1; i<=$n; i++ )); do
read -p "Enter string number $i: " input_string
arr+=("$input_string")
done

# Print the array


echo "The strings you entered are:"
for string in "${arr[@]}"; do
echo "$arr"
done

The resultthe
Enter will be:
number of strings you want to input: 3
Enter string number 1: a
Enter string number 2: 123 b
Enter string number 3: c
The strings you entered are:
a
123 b
c
Do Khang Bash command------------------------------------------ Bash
script
6. Bash quotes and quotations
a) Escaping Meta characters
Escaping will suppress a special meaning of meta characters and therefore meta characters will be read
by bash literally. To do this we need to use backslash \ character.

#!/bin/bash

#Declare bash string variable


BASH_VAR="Bash Script"

echo $BASH_VAR
echo \$BASH_VAR
echo \\\$BASH_VAR
echo \\

The result
Bash will be:
Script
$BASH_VAR
$BASH_VAR
\

b) Single quotes
Single quotes in bash will suppress special meaning of every meta characters within it. Therefore meta
characters will be read literally.
If a pair of single quotes is placed inside another pair of single quotes, the outer one will suppress the
the inner one, allowing every meta character within the inner one to function normally again.

#!/bin/bash

v="Hello"
echo $v
echo ' $v "$v" '
echo ' '$v' ''$v'' '''$v''' '

echo \'$v''
# 123456

echo '\'$v\'''
# 123456789
Do Khang Bash command------------------------------------------ Bash
script
The result will be:
Hello
$v "$v"
Hello $v Hello
'Hello
\Hello'

As for echo \'$v'', \(1) suppresses '(2), allowing $(3) to access the variable v(4), hence $v becomes
Hello. ‘(5,6) form a pair of single quotes that contains nothing.

As for echo '\'$v\''', '(1,9) suppress both \(2) and '(3,8). As '(3,8) is suppressed, $(4) and \(6)
works normally, which leads to $v becomes Hello and '(7) is suppressed.
c) Double quotes
Double quotes in bash will suppress special meaning of every meta characters except $, \ and `.
Every pair of double quotes nested inside an outmost pair of double quotes will not be displayed. In case
we need to display them, suppress the inner pair with the backslash.
Every pair of single quotes nested inside a pair of double quotes will always do nothing and be
displayed normally.

#!/bin/bash

v="Hello"
echo $v
echo " $v "$v" ""$v"" """$v""" "
echo " $v '$v' ''$v'' '''$v''' "
echo " \"$v\" "

echo "\'$v'\""
# 123456789

The result will be:


Hello
Hello Hello Hello Hello
Hello 'Hello' ''Hello'' '''Hello'''
"Hello"
\'Hello'"

As for echo "\'$v'\"", '(3,6) is already suppressed by "(1,9) hence $v becomes Hello. Thus, \(2)
simply do nothing. Because of \(7), "(8) is suppressed and displayed normally.
Do Khang Bash command------------------------------------------ Bash
script
7. Redirections
Every program opens 3 files: STDIN, STDOUT and STDERR, whose file descriptor is 1,2 and 3
respectively.
By default, STDIN goes to the terminal keyboard, STDOUT and STDERR go to the terminal output
screen.
/dev/null is a virtual device, called null device, that discards all data written to it and provides an
empty stream of data when read from. Basically, it works as a normal file, apart from the fact that this
file does not exist.
com < Foo Redirect the input of the command com from file Foo
com (f)> Foo Redirect the output of the command com into file Foo
 no f Redirect only STDOUT
 f = 1 Redirect only STDOUT
 f = 2 Redirect only STDERR
 Foo exists Overwrite the content of Foo
 Foo does not exist Create Foo and put new the content into it
com (f)>> Foo Redirect the output of the command com into file Foo
 no f Redirect only STDOUT
 f = 1 Redirect only STDOUT
 f = 2 Redirect only STDERR
 Foo exists Append the new content to the existing content of
Foo
 Foo does not exist Create Foo and put the new content into it

If you want to redirect both STDOUT and STDERR, the idea is to redirect STDOUT first, then redirect
STDERR to where STDOUT had been redirected, or vice versa.
com > /dev/null 2>&1 Redirect the STDOUT output of the command com into the
null device, then redirect the STDERR output to where
STDOUT goes, which is the null device as well.
com 2> /dev/null 1>&2 Redirect the STDERR output of the command com into the
null device, then redirect the STDOUT output
accordingly.

You might also like