Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
SEARCH
Search Search
LINUX
Bash shebang
Setting permission
Print messages
using variables
Environment variables
User variables
Command substitution
Math calculation
if-then statement
Numeric Comparisons
String Comparisons
File Comparisons
Linux Server Administration Web Development Pentesting
pwd ; whoami
#!/bin/bash
#!/bin/bash
# This is a comment
pwd
whoami
chmod +x ./myscript
./myscript
Print Messages
As we know from other posts, printing text is
done by echo command
#!/bin/bash
Linux Server Administration Web Development Pentesting
whoami
Using Variables
Variables allow you to store information in the
bash script for use with other commands in the
script.
#!/bin/bash
User variables
In addition to the environment variables, a bash
script allows you to set and use your own
variables in the script.
#!/bin/bash
# testing variables
Linux Server Administration Web Development Pentesting
chmod +x myscript
./myscript
Command substitution
One of the best features of bash scripts is the
ability to extract information from the output of
a command and assign it to a variable so you
can use that value anywhere in your script
mydir=`pwd`
Linux Server Administration Web Development Pentesting
#!/bin/bash
mydir=$(pwd)
echo $mydir
Math calculation
You can perform basic math calculations using
$[] format
#!/bin/bash
var1=$(( 5 + 5 ))
echo $var1
var2=$(( $var1 * 2 ))
echo $var2
if command
then
commands
#!/bin/bash
if pwd
then
fi
Linux Server Administration Web Development Pentesting
#!/bin/bash
user=likegeeks
then
fi
if-then-else Statement
The if-then-else statement looks like this
if command
then
commands
else
commands
#!/bin/bash
user=anotherUser
Linux Server Administration Web Development Pentesting
fi
if command1
then
commands
elif command2
then
commands
Linux Server Administration Web Development Pentesting
#!/bin/bash
user=anotherUser
if grep $user /etc/passwd
then
elif ls /home
fi
Numeric Comparisons
You can perform numeric comparison between
two numeric values using numeric comparison
checks as on this list
#!/bin/bash
val1=6
if [ $val1 -gt 5 ]
then
else
fi
#!/bin/bash
user ="likegeeks"
if [$user = $USER]
then
Linux Server Administration Web Development Pentesting
#!/bin/bash
val1=text
val2="another text"
then
echo "$val1 is greater than $val2"
else
fi
Linux Server Administration Web Development Pentesting
#!/bin/bash
val1=text
val2="another text"
then
else
fi
then
else
fi
sort myfile
likegeeks
Likegeeks
File Comparisons
This is the best and most powerful and most
used comparison in bash scripting there are
many le comparisons that you can do in bash
script
-e le Checks if le exists
#!/bin/bash
mydir=/home/likegeeks
if [ -d $mydir ]
then
cd $ mydir
ls
else
fi
Linux Server Administration Web Development Pentesting
LINUX
for command
Nesting Loops
for Command
The bash shell provides the for command to
allow you to create a loop that iterates through
a series of values. This is the basic format of
the bash shell for command
do
commands
done
do
done
done
#!/bin/bash
file="myfile"
do
done
Linux Server Administration Web Development Pentesting
IFS=$'\n'
#!/bin/bash
file="/etc/passwd"
IFS=$'\n'
do
done
IFS=:
#!/bin/bash
do
if [ -d "$file" ]
Linux Server Administration Web Development Pentesting
fi
done
do
done
do
other commands
done
#!/bin/bash
var1=5
do
echo $var1
var1=$[ $var1 - 1 ]
done
Nesting Loops
A loop statement can use any other type of
command within the loop, including other loop
commands. This is called a nested loop.
#!/bin/bash
do
done
done
#!/bin/bash
IFS=$'\n'
do
IFS=:
do
done
done
Linux Server Administration Web Development Pentesting
break command
Linux Server Administration Web Development Pentesting
#!/bin/bash
for var1 in 1 2 3 4 5 6 7 8 9 10
do
if [ $var1 -eq 5 ]
then
break
fi
done
do
if [ $var1 -eq 5 ]
then
break
fi
var1=$(( $var1 + 1 ))
done
do
then
continue
fi
done
#!/bin/bash
do
echo "finished."
#!/bin/bash
IFS=:
do
echo "$folder:"
do
if [ -x $file ]
then
fi
done
done
Thanks
Linux Server Administration Web Development Pentesting
LINUX
Shift command
Standardizing Options
Reading password
Reading from a le
Reading parameters
The bash shell assigns special variables, called
positional parameters, to all of the command
line parameters entered
#!/bin/bash
echo $0
echo $1
echo $2
echo $3
Linux Server Administration Web Development Pentesting
#!/bin/bash
total=$[ $1 + $2 ]
#!/bin/bash
Linux Server Administration Web Development Pentesting
Testing parameters
If the script is run without the parameters and
your code expecting it, youll get an error
message from your script.
#!/bin/bash
if [ -n "$1" ]
Linux Server Administration Web Development Pentesting
fi
Counting parameters
You can count how many parameters were
entered on the command line. The bash shell
provides a special variable for this purpose.
#!/bin/bash
./myscript 1 2 3 4 5
#!/bin/bash
count=1
do
count=$(( $count + 1 ))
done
count=1
do
count=$(( $count + 1 ))
done
Shift command
The shift command has some little risk in Linux
bash scripting it literally shifts the command
line parameters in their relative positions.
#!/bin/bash
count=1
Linux Server Administration Web Development Pentesting
shift
done
#!/bin/bash
echo
Linux Server Administration Web Development Pentesting
esac
shift
done
$ ./myscipt a b c d
#!/bin/bash
while [ -n "$1" ]
do
case "$1" in
--) shift
break ;;
esac
shift
Linux Server Administration Web Development Pentesting
count=$(( $count + 1 ))
done
#!/bin/bash
while [ -n "$1" ]
do
case "$1" in
-b) param="$2"
shift ;;
--) shift
break ;;
esac
shift
done
count=1
do
Linux Server Administration Web Development Pentesting
./myscript -a -b test1 -d
Standardizing Options
When you start your Linux bash scripting, its
completely up to you to choose which letter
options you select to use and how you select to
use them.
-c Produces a count
-d Species a directory
-e Expands an object
-x Excludes an object
#!/bin/bash
read name
#!/bin/bash
read -p "Enter your name: " first last
#!/bin/bash
#!/bin/bash
then
fi
Reading password
In Linux bash scripting Sometimes you dont
want that input to display on the screen like
entering a password.
Reading from a le
The read command reads a single line of text
from the le on each call.
#!/bin/bash
count=1
do
Linux Server Administration Web Development Pentesting
Thanks.
Linux Server Administration Web Development Pentesting
Standard le descriptors
Closing le descriptors
Standard le descriptors
Everything is a le in Linux and that includes
input and output and Linux identies each le
using the le descriptor.
STDIN
This stands for the standard input to the shell.
For a terminal interface, the standard input is
the keyboard.
STDERR
This le descriptor standard error output for the
shell
Redirecting errors
As we see the STDERR le descriptor is set to
the value 2. We can redirect the errors by
Linux Server Administration Web Development Pentesting
cat ./myfile
Redirecting Output in
Scripts
There are two methods for redirecting output in
shell scripting
Temporarily redirection
Linux Server Administration Web Development Pentesting
#!/bin/bash
Permanent redirections
If you have lots of data that youre redirecting
in your script, it would be hard to redirect every
echo statement. Instead, you can redirect to a
specic le descriptor for the duration of the
script by using the exec command.
#!/bin/bash
exec 1>outfile
exec 1>myfile
#!/bin/bash
count=1
do
count=$(( $count + 1 ))
done
Creating input le
descriptors
You can redirect input le descriptors in shell
scripting exactly the same way as output le
descriptors. Save the STDIN le descriptor
location to another le descriptor before
redirecting it to a le.
#!/bin/bash
exec 6<&0
count=1
do
Linux Server Administration Web Development Pentesting
case $answer in
y) echo "Goodbye";;
esac
exec 3>&-
#!/bin/bash
exec 3>&-
descriptors
The lsof command lists all the open le
descriptors on the entire Linux system
lsof -a -p $$ -d 0,1,2
#!/bin/bash
lsof -a -p $$ -d 0,1,2,3,6,7
Linux Server Administration Web Development Pentesting
Suppressing Command
Output
Sometimes you dont want to see any output
this often occurs if youre running a script as a
background process (we will discuss how to
make you shell script run in the background in
the next posts)
Thanks
LINUX
Linux signals
Stop a process
Pause a process
Trapping signals
Viewing jobs
Linux signals
There are more than 30 Linux signals that can
be generated by the system and applications
and this is the most common Linux system
signals that youll run across in your Linux bash
script writing
17 SIGSTOP Unconditionally
stops, but doesnt terminate, the process
Generating signals
The bash shell allows you to generate two basic
Linux signals using key combinations on the
keyboard. This feature comes in handy if you
need to stop or pause a running bash script
Stop a process
The Ctrl+C key combination generates a SIGINT
signal and sends it to any processes currently
running in the shell which simply stops the
current process running in the shell.
$ sleep 100
Ctrl+C
Pause a process
The Ctrl+Z key combination generates a
Linux Server Administration Web Development Pentesting
$ sleep 100
Ctrl+Z
ps l
Linux Server Administration Web Development Pentesting
kill processID
Trapping signals
The trap command allows you to specify which
Linux signals your shell script can watch for and
intercept from the shell. If the script receives a
signal listed in the trap command, it prevents it
from being processed by the shell and instead
handles it locally.
#!/bin/bash
count=1
while [ $count -le 10 ]
do
sleep 1
count=$(( $count + 1 ))
done
#!/bin/bash
count=1
do
sleep 1
count=$(( $count + 1 ))
done
trap
You can reissue the trap command with new
options
#!/bin/bash
count=1
do
sleep 1
count=$(( $count + 1 ))
done
count=1
do
sleep 1
count=$(( $count + 1 ))
done
Linux Server Administration Web Development Pentesting
#!/bin/bash
count=1
do
sleep 1
count=$(( $count + 1 ))
done
trap -- SIGINT
count=1
do
Linux Server Administration Web Development Pentesting
$ ./myscript
Crtl+C
#!/bin/bash
count=1
do
sleep 1
count=$(( $count + 1 ))
done
$ ./myscipt &
Linux Server Administration Web Development Pentesting
done.
Viewing jobs
The jobs command allows you to view the
Linux Server Administration Web Development Pentesting
do
sleep 10
count=$(( $count + 1 ))
done
Then run it
$ ./myscript
jobs l
$ ./myscript
Now it is stopped
$ bg
$ fg 1
Scheduling a job
The Linux system provides a couple of ways to
run a bash script at a preselected time: the at
command and the cron table
The at command
MM/DD/YY, or DD.MM.YY
A text date, such as Jul 4 or Dec 25, with or
without the year
Now + 25 minutes
10:15PM tomorrow
10:15 + 7 days
$ at -f ./myscript now
$ atq
Linux Server Administration Web Development Pentesting
$ atrm 18
Scheduling scripts
Using the at command to schedule a script to
run at a preset time is great, but what if you
need that script to run at the same time every
day or once a week or once a month.
30 10 * * * command
30 16 * * 1 command
crontab e
30 10 * * * /home/likegeeks/Desktop
/myscript
$ rm -f /var/run/crond.pid
/etc/cron.daily
/etc/cron.weekly
/etc/cron.monthly
$HOME/.bash_prole
$HOME/.bash_login
$HOME/.prole
Thanks.
LINUX
Creating a function
Using functions
Recursive function
Creating libraries
Creating a function
You can create a function like this
functionName {
Or like this
functionName() {
Using functions
#!/bin/bash
Linux Server Administration Web Development Pentesting
do
myfunc
count=$(( $count + 1 ))
done
myfunc
#!/bin/bash
Linux Server Administration Web Development Pentesting
count=$(( $count + 1 ))
done
function myfunc {
#!/bin/bash
function myfunc {
myfunc
function myfunc {
Linux Server Administration Web Development Pentesting
#!/bin/bash
function myfunc {
}
Linux Server Administration Web Development Pentesting
function myfunc {
}
result=$( myfunc)
Passing parameters to a
function
We can deal with bash functions like small
snippets that we can reuse and thats ok but we
need to make the function like an engine, we
give it something and it returns another thing
based on what we gave.
myfunc $val1 10 20
#!/bin/bash
function addnum {
if [ $# -eq 0 ] || [ $# -gt 2 ]
then
echo -1
elif [ $# -eq 1 ]
then
echo $(( $1 + $1 ))
else
Linux Server Administration Web Development Pentesting
value=$(addnum 10 15)
echo $value
value=$(addnum 10)
echo $value
value=$(addnum)
echo $value
value=$(addnum 10 15 20)
echo $value
#!/bin/bash
function myfunc {
echo $(( $1 + $2 ))
if [ $# -eq 2 ]
then
value=$( myfunc)
else
fi
if [ $# -eq 2 ]
then
value=$(myfunc $1 $2)
else
fi
Handling variables in
bash functions
Every variable we use has a scope, the scope is
where the variable is visible
Local
Global variables
Global variables are variables that are visible
and valid anywhere in the bash script. If you
dene a global variable in the main section of a
script, you can retrieve its value inside a
function.
#!/bin/bash
function myfunc {
value=$(( $value + 10 ))
myfunc
Linux Server Administration Web Development Pentesting
Local variables
Any variables that the bash function uses
internally can be declared as local variables. To
do that, just use the local keyword in front of
the variable like this
#!/bin/bash
Linux Server Administration Web Development Pentesting
temp=4
myfunc
Passing arrays to
functions
The art of passing an array variable to a bash
function can be confusing. If you try to pass the
array variable as a single parameter, it doesnt
work
#!/bin/bash
function myfunc {
myfunc $myarray
#!/bin/bash
function myfunc {
local newarray
newarray=("$@")
myarray=(1 2 3 4 5)
Linux Server Administration Web Development Pentesting
Recursive function
This feature enables the function to call itself
from within the function itself
5! = 1 * 2 * 3 * 4 * 5
x! = x * (x-1)!
echo 1
else
local temp=$(( $1 - 1 ))
fi
result=$(factorial $value)
Creating libraries
Now we know how to write functions and how
to call them but what if you want to use these
bash functions or blocks of code on
dierent bash script les without copying
and pasting it over your les.
Linux Server Administration Web Development Pentesting
. ./myscript
function addnum {
echo $(( $1 + $2 ))
#!/bin/bash
Linux Server Administration Web Development Pentesting
. /home/likegeeks/Desktop/myfuncs
$ addnum 10 20
Linux Server Administration Web Development Pentesting
Thank you.
Linux Server Administration Web Development Pentesting
LINUX
Substituting ags
Replacing characters
Limiting sed
Deleting lines
Useful examples
This is our le
$ sed -e '
> s/This/That/
$ cat mycommands
Linux Server Administration Web Development Pentesting
Substituting ags
Look at the following example carefully
$ cat myfile
text
$ cat myfile
Replacing characters
Suppose that you want to substitute the C shell
for the bash shell in the /etc/passwd le, youd
have to do this
$ sed 's/\/bin\/bash/\/bin\/csh/'
/etc/passwd
Limiting sed
The commands you use in the sed command
apply to all lines of the text data. If you want to
apply a command only to a specic line or a
group of lines, there are two forms
$ sed '/likegeeks/s/bash/csh/'
/etc/passwd
Deleting lines
If you need to delete specic lines of text in a
text stream, you can use the delete command
Modifying lines
The change command allows you to change the
contents of an entire line of text in the data
stream. All you have to do is to specify the line
that you want to change.
Transforming characters
The transform command (y) works on a single
character like this.
$ cat newfile
Cool right?
Useful examples
We can use the read command is to use it in
conjunction with a delete command to replace
a placeholder in a le with data from another
le. Suppose we have the following le called
newle
$ Sed '/DATA>/ {
Linux Server Administration Web Development Pentesting
LINUX
command options
Built-in variables
Data variables
Structured Commands
Formatted Printing
Built-In Functions
like this
string we provide.
This is our le
print $1 text $6
{print $0}
BEGIN {
FS=":"
}
Linux Server Administration Web Development Pentesting
Built-in variables
The awk command uses built-in variables to
reference specic features within the program
data
Linux Server Administration Web Development Pentesting
1235.9652147.91
927-8.365217.27
36257.8157492.5
$ awk 'BEGIN{FIELDWIDTHS="3 5 2
5"}{print $1,$2,$3,$4}'
Linux Server Administration Web Development Pentesting
Person Name
(222) 466-1234
Linux Server Administration Web Development Pentesting
$ awk '
BEGIN{
print ENVIRON["HOME"]
print ENVIRON["PATH"]
Linux Server Administration Web Development Pentesting
$ awk 'BEGIN{FS=","}{print
$1,"FNR="FNR}' myfile myfile
BEGIN {FS=","}
{print $1,"FNR="FNR,"NR="NR}
BEGIN{
test="This is a test"
print test
}'
Structured Commands
The awk programming language supports the
standard if-then-else format of the if statement.
You must dene a condition for the if statement
to evaluate, enclosed in parentheses.
Here is an example
10
15
Linux Server Administration Web Development Pentesting
$ awk '{
x = $1 * 2
print x
}' testfile
Linux Server Administration Web Development Pentesting
x = $1 * 2
print x
} else
{
x = $1 / 2
print x
}}' testfile
cat myfile
$ awk '{
total = 0
i = 1
while (i < 4)
{
total += $i
i++
avg = total / 3
print "Average:",avg
}' testfile
Linux Server Administration Web Development Pentesting
$ awk '{
total = 0
i = 1
while (i < 4)
{
Linux Server Administration Web Development Pentesting
avg = total / 2
}' testfile
$ awk '{
total = 0
{
Linux Server Administration Web Development Pentesting
}' testfile
Formatted Printing
The printf command in awk allows you to
specify detailed instructions on how to display
data.
%[modier]control-letter
}'
Built-In Functions
The awk programming language provides quite
a few built-in functions that perform
mathematical, string, and time functions. You
can utilize these functions in your awk scripts
Mathematical functions
If you love math, those are some of the
mathematical functions you can use with awk
toward 0
String functions
There are many string functions you can check
the list but we will examine one of them as an
example and the rest is the same
$ awk '
function myprint()
BEGIN{FS=":"}
{
myprint()
}' /etc/passwd
Linux Server Administration Web Development Pentesting
Thank you
Admin
https://likegeeks.com
RELATED ARTICLES