0% found this document useful (0 votes)
18 views

(English (Auto-Generated) ) Bash Scripting Tutorial For Beginners (DownSub - Com)

Uploaded by

xm11074
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

(English (Auto-Generated) ) Bash Scripting Tutorial For Beginners (DownSub - Com)

Uploaded by

xm11074
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 41

welcome to this crash course on bash

scripting throughout this course Herbert

will teach you a wide range of topics

including basic commands writing your

first bash script working with variables

mastering control structures and diving

into powerful text manipulation tools

like awk and said get ready to unlock

the full potential of bash scripting and

enhance your productivity by automating

tasks streamlining processes and making

your workflow more efficient hello

everyone and welcome to this

introduction course to bash shell

scripting this course is aimed at anyone

who is new to Shell scripting people who

want to expand their knowledge or for

those who want to refresh their

knowledge my name is Herbert and I will

be your instructor for this course I've

been in the it sector as a system

engineer since 2009 I've dealt with

multiple systems ranging from Windows

server to Linux servers and in the last

few years I started specializing in

Automation and Development I've been

doing YouTube content creation since

2017 up until now and I've already

created a course on Linux which might be

a good starting point if you're


completely new to Linux I want to learn

more about the basics of the operating

system itself

now what is Bash Bash is short for Born

Again shell it replaced the born shell

in the glue Linux project which was the

default shell for Unix operating systems

a shell is a user interface for ease of

use it makes it easy for the user to

manage the operating system without

knowing all of the inner workings and

complexity of the operating system

itself

now why would you learn bash well the

reason you want to learn bash is because

it's currently the most popular shell

scripting language for the Linux

operating system bash has been around

forever it has been used since the early

days of Linux and it has stood the test

of time ever since it's also included in

Mac OS and in Windows when you're using

the windows subsystem for Linux

now why would you not use bash well even

though bash is considered a programming

language it obviously lacks some

features for example the ability to do

object oriented programming is not

available in bash python would obviously


be the Preferred Choice here if you're

looking to create more advanced scripts

that allow object-oriented programming

speaking of python bash is also more

complex in its syntax When comparing

python syntax to bash one could say that

bash is a lot harder to read and write

not only python is often a better choice

for more advanced scripting newer tools

like ansible also make it a lot easier

for you to manage multiple systems which

is a lot harder to do with bash of

course ansible and python are often

overkill for simple scripts and using

one does not exclude the other bash is

often used in tandem with tools like

ansible or integrated in Python scripts

this is exactly the reason why you

should learn bash just knowing the

basics could mean a big difference in a

lot of situations sometimes the old

trusty tools are still the most reliable

what will you need for this course

I aimed this course at the standard

Windows user so I built the course

around the windows subsystem for Linux

AKA WSL

since we will be only using command line

tools and no GUI WSL seemed like the

obvious choice
and I also have a video explaining how

to install WSL on Windows

if you're running a true Linux distro

even better if you're using a Mac you

can follow along in your terminal window

but first make sure that you have bash

set as your preferred shell

small disclaimer basic Linux knowledge

is required if you're completely new to

Linux or even new to bash I would

suggest you at least follow along with

the Linux guide that I have on my

channel it's going to give you a good

basic understanding of how the Linux

operating system works

before we start with actual scripting

let's first do some basic commands in

the terminal let's look at an example of

two very simple commands to display text

in the command line

the first one is called echo which will

display the text you pass it as an

argument

we will write the command Echo and then

we pass it some text like so

we just type in Echo hello and so we can

dissect this by looking at Echo as the

command and hello as the argument

we will learn more about arguments later


in this course in this case we talk

about a positional argument

now we can see the output that says

hello which is the word we gave it as an

argument

let's try and see how another command

the cat command compares to this the cat

command displays the contents of a file

but right now we don't have one so let's

first create a file with our text editor

Vim in this course we're always going to

be using Vim because it's a good text

editor that comes with almost all Linux

distributions

plus it's actually not that hard to use

if you get the hang of it I myself have

written multiple scripts in bash and

python with Vim so it's definitely a

good text editor unless you want to

start writing some serious scripts or

software in that case a decent Gooby

text editor like vs code atom or Sublime

are better options

let's create a new file with Vim by

typing Vim

textfile.txt and let's write something

in it to write something in Vim press

the I button and you will enter the

insert mode

from this mode you can start writing


text let's write hello world in this

file now we press the escape button and

you will see that the insert mode is now

gone we have exited the insert mode and

we're back into command mode and once

you're back into the regular command

mode you can press the colon W to write

the file and this will make sure the

changes we made are actually done and

saved to the disk and then we can press

Q to exit the file

also to make life simpler we can go into

fim make some changes and combine the

colon W and colon Q to write colon WQ

this will automatically write the file

and quit film at the same time

if you made any changes you don't want

to save you can ignore the changes by

typing colon queue exclamation mark

which will quit Vim while ignoring any

changes made

now that we created our file let's try

to print the contents of the file with

the cat command this command will print

out whatever is in the first positional

argument in our case it's the name of

the file we just created so we just type

in cat text file.txt and we should see

the contents of the file printed here


okay great

we can now print our own text and also

text files to the terminal

this may not sound like much but it's

something that you will use a lot when

writing bash Scripts

so now finally we are going to write a

shell script with the knowledge we just

gathered in the previous section start

off by first opening your film text

editor

and name the text file

shelltest.sh like so Vim space

shelltest.sh

now that we have our text editor opened

let's try another mode of writing text

in Vim the append mode instead of

pressing I on your keyboard press the A

Button this will append your text rather

than insert it with the insert mode you

write the character before the cursor

with the append mode you write the

character after the cursor now in this

case it doesn't matter of course because

it's a new file but I thought I would

mention it anyways since sometimes it

can come in handy let's now start with

our shell script

in Vim write Echo hello world and write

and quit the file by pressing the insert


or append mode writing Echo hello world

then pressing the escape button and then

writing colon WQ

now let's see if we can actually find

the file in here using the ls command

which will list all the files in our

current directory as you can see the

file is there and we can verify the

location by looking at the terminal's

current location over here which says

the tilde symbol and the tilde symbol

indicates that we are in our current

home directory by typing PWD we can

verify that we are indeed in the home

directory PWD stands for print working

directory and this way we can print the

directory that we are currently working

in which is indeed our home directory

now let's run our file by providing the

command line with the command line

interpreter

which is Bash space

shelltest.sh

this will output the command we entered

in the shell script using the bash

interpreter

but when we type in Echo dollar sign

shell we can verify that we are actually

running in a bash shell so should we


really have to specify it

well the short answer is yes just

because we are running in a bash shell

that does not mean that Linux is going

to assume every file we want to run is

also in bash we should always provide an

interpreter for our shell script to use

the correct type of shell

that does not mean however that we

shouldn't make it easier for ourselves

we can actually provide the command line

interpreter in the shell script Itself

by typing it at the top of our script

in our case we have to provide the full

path to the Shell interpreter

let's copy our output from the echo

dollar sign shell command and use it in

our shell script

copy the output by selecting it and

using either Ctrl C or right-clicking

the selection either should work

now let's go back into our shell script

and let's enter the insert mode since we

want to enter all this information in

the beginning of the file press I and

type in pound sign exclamation mark and

then paste in the output of the echo

dollar sign shell command and what we do

here is we provide the shebang so the

pound sign exclamation mark is a way of


telling the shell script which

interpreter to use we follow up the

shebang by providing the full path to

the Shell interpreter and this way the

shell knows which type of shell

interpreter it needs to use we can now

run this file doing period forward slash

shelltest.sh but we will see that

permission is denied and we need to give

the file permission to be executed this

is because in Linux we need to give

files permission to act as an executable

file

let's have a look at this when we type

in LS minus L which is a long format of

the ls command

which is another type of argument we

call a flag so the minus L here is

called a flag we give as an argument to

the ls command we are actually asking

the ls command to provide the long

format which will display some more

information about the files and

directories

we can see in our permissions that we do

not have executable permissions yet if

you want to learn more about the basics

of file permissions you should look at

my Linux for beginners tutorial


let's give our file executable

permissions by typing in chmod or smart

U plus X space shelltest.sh

we want to provide U plus X because this

will give only the owner user permission

to execute the file rather than the

entire group or anybody on the system

it's good to have this discipline baked

into your head although on a development

environment it doesn't really matter

very much

okay now we can finally run our shell

script by typing in Period forward slash

shelltest.sh

and we will see the output on the

terminal now that we finally have the

basics out of the way we can actually

start writing some bash Scripts

to understand a little bit better what

variables do in bash have a look at this

script so in this script you have a

classic example of a copy command where

we copy something from to a location

underneath that we have the same

location paths twice typed out

completely now this is something that

you want to avoid as much as you can

underneath that we have a better option

where we actually Define a location path

in a variable called my location from


now this is quite a long variable name

you could actually just Define something

like loc underscore from which would be

better to make it a little bit shorter

but it's just you know it's just for

demonstration purposes how this would

work so you could understand if you

would have a very long path here you

could have that very long file location

stored in a variable and then you could

actually reuse that variable over and

over again like we did in the example

below that so let's now have a look at

how we can actually use use this in an

example so we can either type our name

like this first name equals let's say

Herbert and that's how we can actually

use these variables by typing like Echo

hello and then typing the variable like

so so that's how it would work like

inline or in the command line itself but

we can actually also just write a script

to demonstrate a little bit better how

variables work so just type in Vim

hello there dot sh

and then we'll do the insert mode with

the shebang forward slash bin forward

slash bash and then over here we'll

Define our first name equals Herbert or


you know your name and then last name

equals lindemann's which is my last name

and I will just do like this Echo

hello dollar sign first name

and then we'll do dollar sign last name

and then we'll exit with WQ and now the

only thing we need to do is smart U plus

X hello there dot sh and now we can run

it and now we can see that our name is

printed out here

just like that

so now we actually type this statically

but we can actually also ask the user

for input like so so let's open a new

shell script with Vim interactive shell

dot sh and we'll do the same we'll

insert then we'll do the shebang bin

Bash

and first of all we'll need to ask the

user like what is your name

so what is your name what is your first

name let's ask and then we'll do a read

statement and we'll read the first name

I will do the same with what is your

last name

and I will read last name

and I will Echo hello

dollar sign first name

space dollar sign last name

and then we'll write in quit


and then we'll do the classic smart U

plus X

and then interactive shell.sh and we'll

run it and now it's going to prompt us

for our first name and for our last name

and then it will just print out our

first and last name like so

we could have the terminal display our

own name or anything else provided in a

positional argument as well but first

what is a positional argument a

positional argument is exactly what it

sounds like we place the argument at a

certain position behind the command or

script we want to run

the positional argument can be in

position 1 2 3 and so forth

the positions are always separated by a

space

when working with positional arguments

you expect arguments to be in a certain

position that is separated by a space

and Counting from one position zero is

reserved for the shell itself

now let's have a look at one of these

positional arguments create a new script

by typing Vim pulse argue.sh and enter

the insert mode again we will have the

script taken our first and last name on


position one and two and have it take

these words as positional arguments

let's just write our shebang and write

our one line of code like so

shebang bin bash Echo hello

dollar sign one dollar sign two

now save the file and close fim change

our permissions and let's run the script

again with the positional arguments dot

forward slash pulse argue.sh Herbert

lindemans or whatever your name is here

and as you can see we get the same

output here with only one line of code

one of the most frequently used features

in bash is piping it makes it very easy

to perform a specific action on the

output of the command

let's say the output of a command is

very long and you wish to filter some

things out piping is going to give you

that option

now how does piping work let's have a

look at an example

let's say we want to look at a specific

directory but we just want to filter out

certain files or subdirectories we could

for example use a command like this

so we're typing LS minus l

forward slash R directory in this case

we're using the bin directory at forward


slash user forward slash bin and then

space and then we type the piping symbol

space grep which is something that we

use to filter out specific words and

then we type in Bash

I will see the output is just the bash

binaries that we can see here rather

than the entire bin directory in this

command we forward the output of the ls

command into the next command with the

pipe symbol

this symbol represents a pipe and this

is what we call piping we literally sent

the output from a command before the

pipe symbol to the command behind the

pipe symbol

grip is just an example there are many

more commands that have very powerful

potential when used with piping

when sending output to a file we have to

use different kinds of symbols than the

pipe symbol instead we use the greater

than and double greater than symbols

these symbols will be used to send the

output from a command to a file this can

have many potential use cases the first

thing that comes to mind is logging

something from your script to a log file

and this is something that you'll


definitely use in real life scenarios

let's see how we can use these symbols

first we catch the output of a simple

Echo command start by typing in Echo

hello world greater than hello.txt this

prints hello world into a file called

hello.txt notice that we put the command

before the greater than symbol and the

name of the text file after the greater

than symbol now we can see if this

worked by typing in cat hello.txt and we

should see the output of the echo

command in here now let's try something

different here type in Echo good day to

you greater than hello.txt and let's see

what's the hello.txt file by typing in

cat hello.txt but what's this the file

was overwritten

we don't have our hello world anymore

well this is because the greater than

symbol always overwrites any existing

file

what we need to have is a proper way to

append text rather than overwrite it

this is where the double greater than

symbol comes in this will append any

output to our destination file rather

than overwrite it let's try it out but

first let's remove that original file

with RM space hello.txt then we use Echo


hello world double greater than symbol

hello.txt and we check if the contents

are indeed correct with cat hello.txc

and indeed the text is there

and once we verified this we send

another output to the file using the

double greater than symbol and type in

Echo good day to you double greater than

hello.txt and we once again verify this

output with cap hello.txt and we should

see both outputs here

now imagine using this in combination

with timestamps to see which command ran

at which time and also some error

handling and we're starting to collect

the tools we need to write a real script

we can also feed input into a command by

reversing the greater than symbol we can

use the lesser than double lesser than

or even triple lesser than symbol to get

input from a file multiple lines of text

or a single string of text

let's first look at the lesser than

operator which will get input from a

text file

we will use the word count command as an

example here because it's one of those

commands that has a use case for these

types of operators let's type in WC


minus W hello.txt to get the word count

but what happens here we get a little

more than we asked for as an output the

WC command by default also shows the

file name which is not what we want

if we just want to get the number of

words we need to feed the WC command and

input from the file with the lesser than

operator rather than the file itself as

a positional argument

this can be done like so WC minus w

space lesser than space hello.txt and

this way we will redirect the file to

the WC command rather than passing it as

a positional argument to the command we

will now get to the second way of

feeding data to a command with the

double lesser than operator this is a

great way to supply multiple lines of

text to a command

when we write the double lesser than

operator we will immediately follow it

up with a word that will open and close

the text we want to input basically we

tell the command line hey wait for this

word and then capture everything I wrote

in between the first and second

occurrence

often people will write eof but you can

write whatever you want


let's have a look at how this would work

so we type in cat space

double lesser than symbol eof now we see

that the command line waits for input so

we can keep writing lines of text here

and let's write some text creating a new

line with the enter key and we'll type

in I will enter write sum enter text

here enter and now we close it with the

first word we Supply it and we type

again eof

and now we should see the text that we

wrote here between the two eof

statements

now last but not least we can also

Supply single strings of text to the

command line

this will be done with you guessed it

the triple lesser than operator let's

have a look at another example of the WC

command we use

by default WC will either read a file or

a command output but not actual strings

supplied as positional arguments

the command either an entire file or the

output of a file with one of the lesser

than operator variations let's see how

we can provide a string to this WC

command so we're typing WC minus W again


space

triple lesser than symbol and then we

open with double quotes hello there word

count and now we close again with double

quotes and we should see the word count

printed here in the terminal this is how

we can feed a string into a command and

take note that the string needs to be in

between double quotes otherwise it will

not work

in bash we have a built-in command

called test that will take in a couple

of arguments and show you if the

expression is true or not for example we

can ask a terminal to show us whether or

not a string of text is equal to another

we can write test followed by the

expression but I prefer using square

brackets let's see how that's done so we

just write open square brackets space

and this is important because you need

the space in between hello space equal

sign space again hello followed by

another space and then closing the

square brackets and this will show no

output but when we do Echo dollar sign

question mark we should see output 0

here because the first string of text is

equal to the second and that would give

us a return value of zero dollar sign


question mark Returns the value of the

exit code of the last executed command

we will learn more about exit codes

later for now it's enough to know that

exit code 0 means that the command was

executed without any issues

another example of this would be

comparing numbers with each other for

example again we open the square

brackets Space 1 equals zero space we

close the square brackets and then we do

Echo dollar sign question mark and this

shows us that the values are not the

same because we get a return code one

but we could also use a different

operator here to make sure that the

values are actually numerical

we could use the minus EQ operator for

this

and we do this with opening the square

brackets 1 minus EQ 1 goes to square

brackets

Echo dot assign question mark this also

shows us the same return value exit code

0 which means that the values do equate

though this would throw an error if you

would use alphabetical characters

instead of numerical ones

now for some more powerful stuff


we can actually use these test

expressions and perform an action on it

let's have a look at this more closely

with an actual script

let's create a login script which will

not really log Us in but it will show us

what is possible with these if alif else

statements

create a new script called if elifls.sh

we type in the shebang

we do if open the square brackets

dollar sign open curly braces one comma

comma close curly bases and I'll explain

to you what this means in just a second

equals

your username

close the square brackets

semicolon then and then we follow up

what we actually want to do here

so we want to Echo oh you're the boss

here welcome

then start a new line

alif open square brackets again dollar

sign curly braces one comma comma curly

braces equals help close the square

brackets

semicolon then

Echo just enter your username the else

Echo I don't know who you are but you're

not the boss of me


and then close it with f i now let me

explain to you what we did here so this

script will take in a positional

argument which is a great way to test

how the if statements will work

we start our if statements with an if

followed by the test expression take

note of the square brackets used in

previous section

we test if the first positional argument

is equal to the value we provide take

note of the double comma and the curly

braces this is called a parameter

expansion and it will allow us to ignore

upper and lower cases When comparing the

two values we then end the test operator

with a semicolon and we follow it up by

then and then beginning a new line and

on this line we type what we actually

want to do with set test expression in

this case we just print something out to

the console telling the user the script

has to recognized the username and that

he is indeed the boss of this system

we can also have a script check for

multiples test expressions

we can Define this with an alif

statement this stands for else if

meaning that else if the previous


statement wasn't true test if this is

true

again start a new line we Define a test

expression that will test if the

positional argument is help and if it is

we display a message that shows us

instructions on how to use the script

being an easy script we want to state

that it isn't so hard to use

maybe a little rude but it's all in good

fun

then if none of these statements are

true finally we have the else statement

this will perform an action if none of

the if or elif statements are true

we can display a message saying that the

username was not detected and that the

system will not be buzzed around by

someone that does not have the correct

username

finally to close our if statements we

end it with f i

this closes the entire block of if lfl's

statements and is required

if alif-l's statements are useful

but you won't use them very often if you

want to check for multiple values for

these kinds of things we use case

statements

first of all what is a case statement


well a case statement performs different

actions depending on which case is true

this means that we can Define multiple

options and if the option matches the

case we will perform an action bound to

that option

let's have a look at how this works in a

real script let's try to recreate our

previous exercise with a case statement

instead of the if alif else statements

create a new file with vim login.sh and

type in the shebang and then we start

our case statement by typing in case

space dollar sign and then the variable

expansion with the curly brackets one

comma comma space in and over here we're

going to do something special we're

going to Define multiple options now

this is something that you could also do

with if statements but I'm just

introducing it here with the case

statements since I thought it would be

interesting to see how it works so we

type in our username space and then the

pipe symbol and over here this is

actually like a separator for multiple

options rather than the pipe symbol that

we saw earlier to pipe things through to

different commands in a case statement


it serves a different function over here

it serves as a separator for multiple

options

so username space pipe symbol space and

then another username for example the

administrator and then we close the

bracket

and then we Define what we want to say

or do here so you want to say something

like uh oh you're the boss here welcome

again like we did in the previous

exercise

and then we close this option with

double

semicolons then we Define another option

here for example help like we did in the

previous exercise

we copy the same Echo command now we

close that option with double semicolons

and then what we do here is we Define

this star symbol or asterisk or whatever

you want to call it and this is the

catch all option that we're going to

Define

and the catch all option is like the

default option when none of the options

are true or when no options are given

and then we Define hello there but

you're not the boss of me please enter a

valid username and then we close that


option with double semicolons and then

close that with esac so it's case just

reversed so again like I said before

notice that we have two options in one

line using the pipe symbol again when we

use the pipe symbol in one of the case

statement options we can use it to have

multiple values to test for we Define

our option for help

also Define a catch all our default

option and this is equal to like the

else statement like we saw earlier

meaning that if none of the options are

equal to the input we will perform a

specific action and now we can run our

script and get the results that we

expect

before we get into looping we need to

First extend our knowledge about

variables

we can actually assign multiple values

to one variable collected in a list we

call these kinds of variable lists

arrays

let's see how we can actually create

this in the command line in the command

line type my first list equals

Open brackets 1 Space 2 Space 3 Space 4

space 5 close the brackets


take note of how we start the array with

Open brackets use a space as a separator

for each item and close the array with

the closing bracket

now let's see what the output is when we

try to print this array

just type in Echo and then just like we

would with any other variable

space

dollar sign my first list

and now we will see that the output is

just the first element and this is of

course not what we want to Echo the

entire list we need to specify it like

this

Echo dollar sign

open curly braces my first list

square brackets at symbol close the

square brackets close the curly braces

and this will print out everything in

the list but we can also Define which

item we want to print like this

Echo space dollar sign curly braces my

first list

square brackets and then over here we'll

just type in 0 which is the Index close

square brackets close the curly braces

and this will print out the first item

in the array because we Define the index

in between the square brackets and


because in bash the first item in the

array always has index 0 counting

upwards we will see the first item in

the array but let's say we want to do

something else with all these items in

the array we can do this with a for Loop

now that we have created our array we

want to Loop over the items in it and do

something using a for Loop in our

example we will count the length of each

word in the array by piping the item

output using Echo to the WC command

don't forget to specify the minus n flag

in our Echo command because otherwise it

would also count the new line characters

type in the command line for space item

space in

dollar sign curly braces my first list

square brackets at square brackets curly

braces semicolon space do space Echo

space minus n space dollar sign item

space pipe symbol space WC space minus c

semicolon space done

take note of how we write the for Loop

here we first Define the variable item

which will represent each item in the

array during the loop then we Define the

iterable which is our array

and what shall we actually Define it in


our for Loop we encapsulated in our

curly brackets and add the square

brackets add square brackets after it to

make sure we Loop over the entire array

then we follow it up with a semicolon

space then we type in do and then we

type in what we actually want to perform

here so we'll type in do Echo minus n as

I said the minus n is just a flag for

the echo command to ignore all the new

line characters then space dollar sign

item because the dollar sign item will

represent one of the items that we are

currently looping over space and then

the pipe symbol WC minus C and then we

do again semicolon and then we type in

done

to understand why we need functions in a

bash script we should first consider

this

in some scenarios we have a lot of

repeated code we might want to do a

specific set of commands in a certain

order or we want to run data through a

set of if else statements multiple times

for these scenarios we create functions

these functions are like little programs

within your script that you can run from

within your script

it makes it so that you can make your


code reusable very powerful stuff

because we can save so much time and

lines of code

let's write our first function in bash

let's open up a new file called first

function.sh I will type in the shebang

and then a new line will type in the

name of the function I will just call

this show uptime and then we open and

close the brackets and then we open the

curly brackets we'll type in up equals

dollar sign Open brackets uptime minus P

pipe cut minus C4 minus and then close

the brackets we'll type in since equals

dollar sign Open brackets uptime minus s

close the brackets and again if I'm

going a little bit too fast for you you

can pause the video and I'm gonna go

over what we actually did here I'm going

to dissect everything we did here in

just a second I did a new line again cat

and then we'll use the double lesser

than symbol eof and we'll type a new

line and we'll just create something

pretty here a few dashes I will type in

this machine has been up for dollar sign

curly braces up curly braces it has been

running since since dollar sign curly

brackets since curly braces then a new


line of then we do a new line of dashes

then we end our statement with eof

close the curly brackets and then we

just type in show uptime so let's

dissect this again

first we Define the name of the function

followed by open and close brackets

followed by the curly brackets to Define

what our function does we enter all the

things it needs to do in between the

curly brackets in our case we will show

the uptime of the machine watch how we

catch the output of a command into a

variable using the dollar sign brackets

notation then we do this again in the

next variable we Define the variable in

the same way but we use different flags

for the uptime command and store that

output in the since variable and we can

now create a nice output using these

variables using the cat command and the

redirection we learned earlier in the

course we end by closing the curly

brackets and then we call the function

by just typing it anywhere in the script

as long as it's typed under the function

it's fine because we need to make sure

that the function first is defined

when we Define a variable in our

function it's available to the entire


script by default this might seem okay

but it can actually cause trouble when

you write bigger Scripts

we want to define the variables inside

our functions as local variables so that

they are only available to our function

and not to the entire script

this way we will avoid accidentally

overwriting Global variables which might

cause issues when we are using functions

that share these variable names let's

have a look at what happens when we

don't use local variables

so let's define our variables named up

equals before since equals function and

then we'll just print those out before

we Define the function so we'll just

Echo up an echo since and then now we

will Define the show uptime function

again and we will leave it the way it is

and then Echo up and Echo since and

let's run it and in this example we can

see that the variables are indeed

globally available which is not what we

wanted we'll see also that they are

globally available but we have actually

overwritten the variables that were

defined before the function and then the

function was actually reassigning those


variables because they are not assigned

as local variables let's fix that so the

only thing we need to do to fix it

really is just add local before we

Define the variable in our function so

instead of just writing up and since

equals the commands that we want to use

before the up we'll just enter local

space and then the same goes for since

we'll Define local space and when we run

this we can now see that our variables

are available to the scope of our

function but the global variable is not

overwritten

just like our entire bash script can

have a positional argument so can our

function let's have a look at an example

create a new script called function

pulse argue.sh I will write the shebang

and that will open our

function with the function name open the

brackets open the curly brackets and

then we'll write Echo hello dollar sign

one

and then close the curly brackets and

then we'll write the function name space

and then whatever you want to write here

we'll write our own name so we can write

out whatever set of characters we want

but in this case we wrote Our Own Name


we could even go as far as to pass

positional arguments of the entire

script to the positional argument of the

function and of course functions can

also take in multiple positional

arguments so lots of stuff is possible

here

let's open up the previous file

underneath the echo statement we'll type

an if statement and then we'll say if

dollar sign curly braces 1 comma comma

equals and then your username which in

my case is Herbert close the brackets

semicolon then return zero else

we will return one

and I will close the if statement then

also over here we'll remove this static

name and change it to a positional

argument one and then also if dollar

sign question mark equals one and close

square brackets semicolon then Echo and

then it will write someone unknown

called the function and then we'll close

the if statement and we're writing quits

and let's now try to run this

with tests for example it'll say hello

test but then you'll see that it also

says that someone unknown requested the

function
awk is one of the most useful tools in

the bash arsenal we use awk to filter

file contents or the output of a command

in such a way that we can print out the

most essential parts and get the output

the way we like it to use awk we can

either filter parts of a file or we can

filter parts of a command output by

piping that output into awk let's have a

look at how we can filter through a

simple text file with awk we first

create a test file which contains three

words separated by a space once we

created that file we can put awk to work

type in awk single quote open the curly

brackets print dollar sign 1 close curly

brackets single quotes space the name of

our test file we will see that the

dollar sign one acts as a placeholder

for the first item in the text file we

could also get the second word that

comes after the first word always

separated by space by typing in awk

single quotes curly braces print dollar

sign two close curly braces single quote

and again our test file now that we get

the idea of awk in its default mode

which is using a space character as a

separator we can move on to changing it

into other characters such as a Kawa


let's create a CSV file and add three

values in it again separated by a comma

this time now we can use awk again to

split the values in the CSV file by

adding the minus capital F flag and

specifying the split character

afterwards like this awk minus capital F

comma space open the single quotes

open the curly braces print data sign

one close the curly braces single quote

test csv.csv and now we will see that

the output is also the same as in our

previous examples but we will see that

awk actually used the comma as a

separator character and last but not

least we can also pipe commands into awk

like so type in Echo just get this word

colon hello and now we pipe into awk and

we'll print out number five because this

is the fifth word separated by space and

I will see that the word hello will be

printed out or we can also split this at

the colon symbol like so

Echo just get this word colon hello pipe

into awk and then we specify the minus F

we follow it up with a colon and then

print dollar sign 2 and I will still

have to cut off the first character

which is a space and that will get the


same results as well and that's just the

beginning of course there's a lot more

possible with awk so if you want to

practice you can try using it more often

in your scripts it really pays off to

know this well because you'll do a lot

of output filtering and reformatting in

Bash

there will come a time where you want to

change certain values in text files and

that's where SED or set comes in set is

a command line tool that would allow you

to modify values in a text file using

regular expressions

let's have a look at an example on how

to use SED or set to replace values in a

text file

create a text file called

settest.txt and let's write down some

text here now we will replace the word

fly with Grasshopper just for

demonstration purposes

so we type in set single quotes s

forward slash fly forward slash

grasshopper forward slash g single

quotes and then the name of our text

file which is settest.txt now the

structure of this command is a little

bit daunting but let's break it down

first we start off with the set command


we open the single quotes and start our

regular expression first we enter the

mode we want to use which is s for

substitute meaning we want to substitute

the next word behind the forward slash

with the word after the second forward

slash which is the first one is fly and

then the second one is grasshopper then

after the last we provide the G which

means that we want to do this globally G

stands for globally and globally means

that we want to do this across the

entire text file which means that we

want to change every occurrence we close

it with another single quote and we put

the text file we want to change behind

the entire command let's say we want to

keep the original in a backup file we

can do this by adding the minus I flag

to the command like so so we just do the

same thing we'll just do set minus I dot

original and then we enter the exact

same command we just provided earlier we

can see here that we use the minus I

flag but we don't put a space behind it

instead we write the entire suffix

behind T minus I flag this will create a

backup file which contains the original

content of the file we just changed with


the set command but the original file

will have the changes we desired just

like with awk this is a basic

introduction to set and there will be so

much more to it but as with all things

in it you need to discover this by

yourself by trying it out as much as you

can well this brings us to the end of

the course

You might also like