3 Hour Bash Tutorial – Linux Hint

In this article you will learn how to print a simple Hello World to use condition operators like, case, to use loops like, for, for up to awk, grep, sed scripts and debug bash. In this article we discuss the following topics:

This article covers the following topics on bash scripts:

  1. Hello Bash Screenplay
  2. Diversion to file
  3. Remarks
  4. Conditional statements
  5. Cycling
  6. Script entry
  7. Scriptual output
  8. Sending the output from one script to another
  9. Chain handling
  10. Numbers and arithmetic
  11. Explain the order
  12. massifs
  13. Features
  14. Files and guides
  15. Sending an e-mail based on a script
  16. Curl
  17. Professional menu
  18. Wait for the filesystem with inotify
  19. Introduction to the Grep
  20. Introduction to awk
  21. Introduction to the dog
  22. Debugging bash scripts

1. Hey, Bash scripting

In this topic you will learn the basics of writing basic scripts and how to create a file to write a script to print Hello. You will then know how to make the file executable.

Press CTRL+ALT+T to open the terminal, or you can search the terminal manually. Enter the following command into the terminal

Execution of the above chat command will lead to the following result.

This command displays all available shells on your system, and you can use them all. For this task, you need to check whether or not your system is equipped with a bash shell. To find out the type path, you have to write the command which keystroke in the terminal that specifies the shell path. This path must be written in every bash-script to be able to execute it.

Now open the terminal from your desktop. This can be done manually by opening the desktop and then choosing Open in Terminal or using the Desktop/Command CD in the current terminal. Create a script with the command helloScript.sh.

Open the file helloScript.sh and the following commands in the file.

#! /bin/bash
Bash Welcome Echo script/

Save the file, go back to the terminal and execute the ls command to confirm the existence of the file. You can also use ls -al to get detailed information about your case, resulting in the following results:

You can see on the output that the file is not yet executable. rw-rw- shows that the owner of the file has read and write rights to the file, that other groups also have the same read and write rights, and that the public has read-only rights to the file. To make this script executable, you must execute the following command in your terminal.

$ chmod +x helloScript.sh

Then use the ls -al command to check the access rights to helloScript.sh, which should give the following results.

Now execute the file with the command ‘./helloScript.sh’ in the terminal. To change the content of a file, you can go back to the file. Change the content defined in the echo command and then execute the file again. I hope it produces the desired result.

2. Shipment to file

This topic shows you how to capture shell output or output from one file and send it to another file. To do this, you need to add the following command to your helloScript.sh.

echo hello bash linuxhint audience > file.txt

Save the file and return to the terminal to run your script with ./helloScript.sh. He will show you the following results. Click ls -al to confirm the existence of the new file.

You can also take the shell file with you and save it in a file. For this you need to write the script ‘cat > file.txt’. Save it and run the script. Now everything you write in this shell is stored in the file.txt.

Data
And finish this process by pressing CTRL+D. The script ‘cat > file.txt’ replaces the text with what you write in the terminal. To create a script that can add the contents of File.txt, you need to write Cat >> File.txt in your script. Save the file, execute the script with the command ./helloscript.sh in the terminal. Now everything you write in the terminal is added to the file with the text already in it.

 

3. Notes

Comments do not play a role in the scenario. If you write comments in the script, it doesn’t matter. He explains the code to the current programmer, who was written earlier. You learn these three things in this subject.

  • Notes on one line
  • Multiline comments
  • Delimeter HereDoc

For a comment on one line you can use the # character for the comment. You can write the following code in your helloScript.sh.

#! / Wastebasket / Basket

# it’s the command cat
cat>> file.txt

When programming, you can have multiple lines of code. In this case, you cannot use these comments on one line, line by line. This is going to be the longest process ever. To solve this problem, you may prefer another method of commenting – multiline commenting. Just say before the first comment, and write after the last comment. For a better understanding, please refer to the following scenario.

#! /bin/bash
:
This is a multi-line comment segment
With this script you will learn
How to create a multi-line comment segment

cat>>file.txt

So these lines are not important. They only exist in your script for a better understanding of the code.

Next is the DocDelimeter. Herredok is a phenomenon that interacts with the hull. The visible difference with comments is that the lines under the DocDelimeter are displayed on the terminal, and in the case of comments, the comments are only present in the script after they have been executed. The syntax ofDocDelimeter is given below.

#! /bin/bash cat <<<< hereDocDelimeterthis is a hereDocDelimeterYou can call it what you want hereDocDelimeter.

Run the script and you will get the following result.

4. Contingent statements

In this topic you will learn about if-self operators, conditional operators that use the AND and OR operators.

If you want operator
to write the condition to a segment, specify another one in [ ] before and after the condition. Next, specify the code for your condition, go to the next line, then type and specify the lines of code you want to execute if the condition is true. Finally, use Fi to close the if report. Below is an example code for a script that contains the syntax of the if-operator.

#! / Wastebasket / Basket

count=10
, if [ $count -eq 10 ]
, then
echo, condition would be
fi.

First of all, this script assigns the value 10 to the number of variables. When approaching the if block, [ $count -eq 10 ] is a condition that checks whether the value of the counter variable is equal to 10 or not. If this condition is met, the enforcement procedure shall be transferred to the following operators. Please indicate that if the condition is true, the block of code written after me must be executed. At the end, fi is the keyword that indicates the end of this if-declaration block. In this case, the condition is true, because the $-count is a variable counterpart equal to 10. The condition is true by going to the keyword then and the print state is true in the terminal.

What if the situation is bad? The program doesn’t know what to do because you don’t have another block. In other clocks you can write declarations that have been met if the condition is false. Here is the code you can write in your ‘helloScript.sh’ file to see how another block of your program works.

#! / Wastebasket/Bash

count=11
if [ $count -eq 10 ]
is then
echo where
otherwise
echo is the condition interfering signal
fi

In this programme, the value 11 is assigned to the counting variable. The program checks the operator as. Because if the situation is not right, he goes to the other block and then ignores the whole section. The terminal displays a message that the condition is incorrect.

There is another format for writing a condition. With this method, simply replace the brackets [ ] with (( )) and write a condition in between. Here is an example of this format.

#! / Wastebasket / Basket

count=10
if ((( $count > 9 ))))
then
echo condition where
is different
echo condition error
fi

Running the above code in the helloScript.sh file gives the following result.

if-else as
When you use if-else as a declaration block in your script, the program checks the conditions. In the same way, if you write the example code below in helloScript.sh, you will see that the program first checks the if condition. Because the counting variable has a value of 10. In the first condition if the program checks if the account value is greater than 9, which is true. Next, the statements written in the block as they are executed are subtracted from the block. For example, if we have a case where the condition written in elif is true, the program will only execute the operators written in the elif block and will ignore the block of if and other operators.

#! / Wastebasket/Bash

count=10
if (( $count > 9 ))))
then
echo first condition is where
elif (( $count <= 9 ))
then
echo second condition is where
is different
echo condition is false
fi

AND operator
To use the AND operator in your terms, you must use the && symbol between your terms to check both. For example, if you write the following code in your helloScript.sh, you will see that the program checks both conditions [$age -gt 18 ] && [$age -lt 40 ], that if you are over 18 and under 40, it is a lie in your case. The program ignores the instructions written afterwards and continues printing the other block on the terminal The age is not correct.

#! / Wastebasket / Basket

age=10
if [ $age -gt 18 ] && [ $age -lt 40 ]
then
echo age correct
otherwise
echo age incorrect
fi

If you execute the above code in helloScript.sh, you will get the following result

You can also write a condition in the following format

#! / Wastebasket / Basket

age=30
, si [[ $age -gt 18 &&$age -lt 40 ] ]
than
echo correct age
other
echo incorrect age
fi

The condition is correct in this case because the age is 30 years. You’ll get the following result.

You can also use -a instead of && to use the AND operator in the terms and conditions of your program. It’ll work the same way.

#! / Wastebasket / Basket

age=30
if [ $age -gt 18 -a $age -lt 40 ]
, then
echo age correct
or
echo age incorrect
fi

Save this code in your ‘helloScript.sh’ script and execute it from the terminal.

OK Operator
If you have two conditions and want to comply with the above statements if one or both are true, the OK Operators will be used in these cases. The -o operator is used to represent the OR operator. You can also use the character for this.
Write the following example code in helloScript.sh and run it from the terminal to check the functionality.

#! / Wastebasket/Bash

age=30
if [ $age -gt 18 -o $age -lt 40 ]
, then
echo age correct
or
echo age incorrect
fi

You can also try out different conditions to better understand the operator of the operating room.

Some of the examples are listed below. Save the script in the file ‘helloScript.sh’ and execute the file from the terminal with the command

#! / Wastebasket / Basket

age=30
if [ $age -lt 18 -o $age -lt 40 ]
then
echo age correct
otherwise
echo age incorrect
fi

#! / Wastebasket / Basket

age=30
, if [ $age -lt 18 -o $age -gt 40 ]
, then
echo age is correct
, otherwise
echo age is wrong
fi

#! / Wastebasket/Bash

age=30
if [[ $age -lt 18 ] $age -gt 40 ]]]].
than
correct reverberation time
again
incorrect reverberation time
fi

#! / Wastebasket/Bash

age=30
if [ $age -lt 18 ] | [ $age -gt 40 ]
then
echo age is correct
otherwise
echo age is not correct
fi

5. Hinges

On this subject we will talk about

  • While the hinges
  • For the hinge
  • For loops
  • Suspension and continuation of statements

While the hinges:
While Loop executes a block of code (nested in do…done) if the condition is true, and continues to execute until the condition becomes false. As soon as the situation becomes false, the time loop is over. Go back to your script to write code in a loop. Use the keyword while and then write a check condition. Then use the keyword do, write a series of expressions you want to satisfy if your program condition is correct. You also have to save the status of the raise there, because then the cycle can be continued. Close the loop by writing the keyword. Save the script as helloScript.sh.

#! / Wastebasket/Bash

Number=1
while [ $number -lt 10 ]
do
echo $number
number=$(( number+1 )))).
do

Run the script with the command ‘$./helloScript.sh’ in your terminal and you will see the following result on your terminal

In the While loop, the system first checks whether the condition is correct or not. If the condition is false, the loop is closed and the program is finished. However, if the condition is true, the execution order changes to an expression written after the keyword do. In your case, the number will be printed together with the echo operator. Then we have to name the increment operator, who loops the loop itself. As soon as the status variable has been increased, it is checked again and continued. If the condition becomes false, the loop is closed and the program is terminated.

#! / Wastebasket / Basket

number=1, and [ $number – the 10 ]dodoecho $number=$( number+1 ))done

By the noose:
Until Loop runs the block of code (nested in … ready) if the condition is false, and continues to run until the condition is true. If the condition is met, the cycle continues until it is completed. The syntax of Until loops is almost identical to that of the while loop, except that the word till should be used instead of the word while. In the following example, the number of the variable is given as value 1. In this example, the loop checks the state if it is false, continues and transmits the value of the variable number to the terminal. In addition, we have an operator who refers to the increase of the number variable. It will increase the value and check the status again. The value is reprinted over and over again until the value of the variable becomes Number 10. If the condition becomes false, the program stops working.

#! / Wastebasket / Basket

number=1 to [ $number -ge 10 ]dodoecho $number=$(((( number+1 ))done

Save the above code in your ‘helloScript.sh’ file. Execution with a single order

You will see the following conclusion.

For the hinges:
This is the type of loop in which we specify the condition in which the loop will be executed again. There are basically two ways to write loops in your code. The first method allows you to write numbers for iteration. In the code below, 5 iterations are performed for the loop, as these iterations are defined for the variable i that controls the iterations. Save the code in the helloScript.sh script file.

#! / Wastebasket / Basket

for i in 1 2 3 4 5
to
echo $i
done

Execute the file ‘helloScript.sh’ by entering the following command into the terminal.

You will get the following result for the scenario.

This method seems simple, but what if you want to repeat it 1000 times? It is not necessary to record the number of iterations from 1 to 1000, but to use a different recording method for the loop. With this method, you must specify the start and end points of the iteration as in the following code example for i in {0…10}, because the loop is executed 10 times. The starting point is defined as 0 and the end point of the iteration as 10. It prints the value i at each iteration of the loop.

#! / Wastebasket/Bash

for me in {0…10}
do
echo $i
done

Save the code in the helloScript.sh file. Run the file and you will get the following result.

You can also set the incremental value for the variable that controls the loop. For example, in for i in {0…10…2}, 0 is the start point of the loop, 10 is the end point, and the loop performs the echo editing $i with step 2 in i. In the example below, the program prints 0 at the beginning of the first loop and then increases the value i. The i-value is now 2. The terminal presses 2. This code indicates the value i, i.e. 0,2,4,6,8,10.

#! / Wastebasket / Basket

for me in {0…10…2}
#{Start…End…Increment}
do
echo $i
done

There is another way to write a loop that is common to all programming languages. The following example code uses this method to display the loop. Here, in the instruction ‘ for ( i=0 ; i

#! /bin/bash
for (((( i=0; i<5; i++))

do
echo $i
done

The program enters the cycle. i is initialized with a value of 0 and the condition is verified that i has a value less than 5, which is true in this case. It continues and prints the value i as 0 in the terminal. Then the value i is increased, then the program checks the state again to see if the value is not greater than 5, which is true, and prints the value i, which is equal to 1, again. This wire continues until I have reached the value 5 and the program leaves the loop and is finished.

Save the code. Execute the file from the terminal and the following result is displayed.

Interrupt and continue with report
The interruption report is used to complete the cycle in this condition. For example, in the code below, the loop is run in normal mode until the value i equals 6. As we already mentioned in the code, the for loop ends and further iterations end when I get bigger than 5.

#! / Wastebasket / Basket

for (( i=0; i<=10; i++ ))
do
if [ $i -gt 5 ]
than
break
fi
echo $i
done

Save the script and run the file. He’ll give you the following result.

Continuing the application works in contrast to pausing it. It skips the iteration, where the state is true, and moves on to the next iteration. For example, the loop code below prints the value of variable i from 0 to 20, excluding 3 and 7, on the terminal. As with the instruction like [ $i -eq 3 ] [ $i -eq 7 ], ask the program to skip the iteration if the value of i is 3 or 7, and proceed to the next iteration without printing it.

To better understand this concept, follow the code below.

#! / Wastebasket/Bash

for (( i=0; i<=10; i++ ) ).
doing
if [ $i -eq 3 ] ||| [ $i -eq 7 ]
then
continues
fi
echo doing $i

6. Input scenario

The first example in this topic is about the code in which you can give a command to execute your script and specify values in the script input.

#! /bin/bash
echo $1 $2 $3

This code prints three values on the terminal. Write the above code in the ‘helloScript.sh’ script and write the command in ‘./helloScript.sh’ with three values to be printed on the terminal. In this example BMW means $1, MERCEDES $2 and TOYOTA $3.

If you also specify 0 in the echo operator, the name of the script will also be printed.

#! /bin/bash
echo $0 $1 $2 $3

You can also use arrays for this purpose. To declare an infinitely large array, use the code args=([email protected]), where args is the name of the array and @ which can have an infinite number of values. This type of array declaration can be used if you do not know the size of the input signal. This table assigns a block to each entry and continues to do so until the last entry.

#! / Wastebasket / Basket

args=([email protected]) # You can also specify an array size here
echo ${args[0]} ${args[1]} ${args[2]}.

Save the script in helloScript.sh. Open the terminal and execute the file with the command ‘./helloScript.sh’ whose values represent the elements of the array declared in the script. According to the command used below, BMW equals ${args[0]}, MERCEDES equals ${args[1]} and HONDA equals ${args[2]}.

The following code can be used to declare a table with an infinite number of values and print these values on the terminal. The difference between this example and the previous one is that this example gives all the values representing array elements, and the ‘ echo ${args[0]} ${args[1]} ${args[2]} command used in the previous example gives only the first three values of the array.

#! / Wastebasket/Bash

args=([email protected])
echo [email protected]

You can also print the size of the table by writing echo $# in the script. Save the scenario. Execute the file via the terminal.

#! / Wastebasket / Basket

args=([email protected])
echo [email protected] # prints all elements of the array
echo $# # prints the size of the array

Playing a file with stdin
You can also play a file with ‘stdin’. To read a file using the script, you must first use a certain cycle time in which you write the code to read and print the file line by line on the terminal. Once the loop is complete, enter the path to the stdin file with the keyword ready.

#! / Wastebasket/Bash

on read line
do
echo line
do < ${1:-/dev/stdin}

Save the script in helloScript.sh. Open the terminal and write a command to execute helloScript with the name of the file you want to read. In this case, the file we want to read is placed on the desktop as Untitled Document 1. Both are used to indicate that it is a unique filename, otherwise a single untitled Document Untitled 1 will be treated as multiple files.

./helloScript.sh Anonymous document 1

7. Script output

In this section you will learn more about the standard output and the standard error. The default output is the output stream resulting from commands, while the default output is the location of the command line error messages.

You can redirect the default output and default error to one or more files. The following script code redirects the two files to a single file. Here ls -al 1>file1.txt 2>file2.txt, 1 is the default output and 2 is the default error. The default output is redirected to file1.txt, while the default error is redirected to file2.txt.

#! / Wastebasket / Basket

ls -al 1>file1.txt 2>file2.txt

Save this code in the file helloScript.sh and execute it in the terminal with the command $./helloScript.sh. The first two files are created on the desktop and then their respective output is redirected. You can then use the ls command to check whether or not the files have been created.

Then check the contents of both files.

As you can see, the default output is redirected to file1.txt.

‘file2.txt’ is empty because there is no standard error for the script. Now let’s try to make a standard error. To do this, you need to change the command from ls -al to ls +al. Save the script below, run the file from the terminal, restart both files and view the results.

#! / Wastebasket/Bash

ls +al 1>file1.txt 2>file2.txt

Start the file with the command ./helloScript.sh on the terminal and check the files now.

file1.txt is empty because there is no default output for the script and the default error is stored in ‘file2.txt’, as shown below

You can also create two separate scenarios for this. In this case, the first script records the default output in file1.txt, while the second script records the default error. The two scenarios are listed below with their conclusions.

#! / Wastebasket/Bash

ls -al >file1.txt

 

#! / Wastebasket / Basket

ls +al >file1.txt

You can also use a file to record the standard output and the standard output. Here is a sample script for this.

#! / Wastebasket / Basket

ls -al >file1.txt 2>&1

8. Send the output from one script to another.

Two things are needed to transfer the results from one scenario to another. First of all, both scripts must exist in the same place and both files must be executable. Step 1 is to create two scenarios. Save one as helloScript and the other as secondScript.

Open the ‘helloScript.sh’ file and write the code below.

#! / Wastebasket / Basket

MESSAGE=Hello LinuxHint PublicNews Export MESSAGE./secondScript.sh

This script exports the value stored in the MESSAGE variable, the main target group of Hello LinuxHint, to secondScript.sh.

Save this file and go to another file to encode. To obtain this MESSAGE, write the following code in secondScript.sh and print it in the terminal

#! / Wastebasket / Basket

as an echo of a message from HelloScript: NOTICE

So far, both scripts have their own code to export, receive and print the message in the terminal. Make ‘secondScript’ executable by entering the following command on the terminal.

chmod +x ./secondScript.sh

Now execute helloScript.sh to get the desired result.

9. Treatment of line

The first operation you’re gonna look at is the line equation. Take two user IDs as character strings. Read these values from the terminal and save them in two different variables. Use the if-operator to compare the values of the two variables with the ==operator. Code the operator to indicate that the strings match when they match, and put the strings not match in the other operator, then close the as operator. You will find the script code for this procedure below.

# ! /bin/bash
echo enter Ist string
read st1
echo enter 2 string
read st2

if [ $st1 == $st2 ]
, then
echo strings match
, otherwise
echo strings do not match
fi.

Save the script in helloScript.sh. Run the file from the presentation device and enter two lines for comparison.

You can also check the indicator by entering various data.

You can also check if your program actually compares the lines or if it not only checks the length of the lines.

Check the line smaller or less than You can also check whether the line is smaller or less than Accept user input, read the terminal’s values. Then compare the lines with the first line or not.

# ! /bin/bash
echo enter Ist string
read st1
echo enter 2 string
read st2

if [ $st1 $st2 ]
, then
echo The second line of $st2 is smaller than $st1
, otherwise the
echo lines are
fi.

Record this helloScript.sh and execute it.

data:;base64,%3csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%201267%20592’%3e%3c/svg%3e data:;base64,%3csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%201267%20592’%3e%3c/svg%3e Sie können auch zwei Zeilen verknüpfen. Take two variables, read the terminal lines and include them in these variables. The next step is to create another variable and link the two variables to it by simply writing c=$st1$st2 into the script and then printing it.

# ! /bin/bash
echo enter Ist string
read st1
echo enter 2 string
read st2

c=$st1$st2
echo $c

Save this code in the file helloScript.sh, run the file in the terminal and check the results.

You can also convert your login to upper and lower case
. To do this, just write a script to read the terminal’s values, then use the ^^ character with the variable name to print it in lowercase, and use ^^ to print it in uppercase. Save this script and run the file through the terminal.

# ! /bin/bash
echo enter Ist string
read st1
echo enter 2 string
read st2

echo ${st1^^} # for lowercase
echo ${st2^^} # Large

By including the first letter of capital
, you can also convert only the first letter of a string by simply writing the variable as $[st1^l}.

# ! /bin/bash
echo enter Ist string
read st1
echo enter 2 string
read st2

echo ${st1^l} # for capitals

10. Numbers and arithmetic

In this topic you will learn how to perform various arithmetic operations using scripts. You can also see different methods of doing this here. In the first method, step 1, define two variables with their values, then use an echo operator and the + operator to send the sum of these variables to the terminal. Save the script, run it and check the result.

# ! /bin/bash
n1=4
n2=20
echo $(( n1 + n2 )))).

You can also write a single script to perform various operations such as addition, subtraction, multiplication, division, and so on.

#! /bin/bash
n1=20
n2=4

echo $(( n1 + n2 ))).
echo $( n1 – n2 ))))
echo $( n1 * n2 ))
echo $( n1 / n2 ))
echo $( n1 % n2 )).

The second method for performing arithmetical operations is the use of expr. This expr takes these n1 and n2 other variables into account and then performs the operation.

#! /bin/bash
n1=20
n2=4

echo $(expr $n1 + $n2 )

You can also use a file to perform various operations with expr. Below is an example of a scenario for this purpose.

#! /bin/bash
n1=20
n2=4

echo $(expr $n1 + $n2)echo $(expr $n1 – $n2)echo $(expr $n1 – $n2)echo $(expr $n1 * $n2)echo $(expr $n1 / $n2)echo $(expr $n1 – $n2)echo $(expr $n1 – $n2)echo $(expr $n1 – $n2)echo $(expr $n1 % $n2)

To convert a hexadecimal number to a decimal number
To convert a hexadecimal number to a decimal number, write a script that takes the hexadecimal number of a user and reads the number. We’ll use the bc calculator. Define obase as 10 and ibase as 16. To better understand this procedure, you can use the following script code.

#! / Wastebasket / Basket

echo Enter the hexadecimal number of your choice in
read Hex
echo -n Decimal value $Hex is:
echo obase=10; ibase=16; $Hex | bc

11. Explain the team

The idea behind this command is that bash itself doesn’t have a strong system type, so you can’t limit a variable in bash. However, to allow this kind of behavior, it uses attributes that can be defined by the declared command. The declaration command is a shell-based bash command that allows you to update the attributes that apply to variables in your shell. It allows you to declare and view variables.

When you write the following command, a list of variables already present in the system is displayed.

You can also specify your own variable. To do this, you must use the declaration command with the name of the variable.

Then use the $ declare -p command to check your variable in the list.

To define a variable with a value, use the command below.

$ declare myvariable=11
$ -p declare

Now let’s try to reduce the number of files. Use -r to apply a read-only restriction to the file and then write the variable name and path.

#! /bin/bash
declare -r pwdfile=/etc/passwd
echo $pwdfile

Now let’s try to make some changes to the file.

#! /bin/bash
declare -r pwdfile=/etc/passwd
echo $pwdfile
pwdfile=/etc/abc.txt

Because the pwd file is limited to a read-only file. An error message should appear after executing the script.

12. Schemes

The most important thing is to learn how to declare a table and store values in it. You can save as many values as you want. Write the name of the table and put the values in brackets ( ). You can consult the code below to see how it works.

#! /bin/bash
car=(‘BMW’ ‘TOYOTA’ ‘HONDA’)
echo ${car[@]}

You can also use the table element index to print them. In the following example, for example, BMW is registered in index 0, TOYOTA in index 1 and HONDA in index 2. To print BMW, you have to write ${car[0]} and vice versa.

# ! /bin/bashcar=(‘BMW’ ‘TOYOTA’ ‘HONDA’)echo ${car[@]}# Pressure value using index echo ${car[0]}echo ${car[1]}echo ${car[2]}

You can also print the table indexes. To do this, you need to write $1.5 million, true! is used to display the index, while @ displays the entire array.

#! /bin/bashcar=(‘BMW’ ‘TOYOTA’ ‘HONDA’)echo ${car[@]}echo print index-echo ${! car[@]}

If you want to print the total number of values in an array, write ${#car[@]}, where # stands for the total number of elements.

# ! /bin/bashcar=(‘BMW’ ‘TOYOTA’ ‘HONDA’ ‘ROVER’)echo ${car[@]}echo print index-echo ${!car[@]} echo print Number of echo values ${#car[@]}

Suppose you have declared an array and then want to delete an element. To delete an element, use the unset command with the name of the array and the index of the element you want to delete. If you need one in two. If you need the car array index, just write unset car [2] in your script. The Unset command removes an array element with its array index from the array. For better understanding, read the following code.

/bin/bash
auto= (‘BMW’ ‘TOYOTA’ ‘HONDA’ ‘ROVER’)
car [2]
echo ${ auto[@]}
echo print index
echo ${! auto[@]}
echo print number
echo ${#car[@]}
Save the following code in ‘helloScript.sh’. Run the file with ./helloScript.sh.

Now you know you have to delete an array element, but what if you want to save another value, like MERCEDES in its index, which is 2. After using undo command, write [2]= ‘MERCEDES’ in the following line. Here we go.

# ! /bin/bash
car= (‘BMW’ ‘TOYOTA’ ‘HONDA’ ‘ROVER’)
car[2]
car[2]= ‘MERCEDES’
echo ${auto[@]}
echo print index
echo ${! auto[@]}
echo print number
echo ${#auto[@]}

Save the script and run the file through the terminal.

13. Functions

The functions are usually reusable code lines that can be recalled over and over again. If you want to perform a certain operation over and over again, or if you want to do something again, it’s a sign of using a function in your code. This saves you the time and effort of writing tons of lines over and over again.

Below is an example of the syntax of the function. The most important thing to remember is that you first have to define or specify your function somewhere in the code before you can call it. To define a function in your code, use the function command with the name of the function you want to specify in step 1, then ( ). Step 2 – Enter the function code { }. Step 3 – Call a function with the name of the function where you want to run it.

# ! The /bin/bash function
()
{
echo is a new function
}.
function

You can also define the function parameters. For example, you need each word as an argument, which is given when calling a function. To do this, simply create a function with the syntax described above and write echo $1 in the body of the function, this line displays the first parameter assigned when the function is called. Leave the body, call the function with the name of the function and the words of the parameter you want to display on the terminal.

# ! Function /bin/bash
funcPrint()
{
echo $1
}

HI functionality

Depending on the program, you can use several parameters or arguments and then specify these parameter values in a function call.

Here’s a sample code.

# ! Function /bin/bash
funcPrint()
{
echo $1 $2 $3 $4
}
funcPrint Hi This is Linuxhint

You can also check whether the function is working properly or not.

# ! Function /bin/bash
funcCheck()
{
returnValue= Use function now
echo $returnValue
}

funcCheck

Save the code in the file helloScript.sh and execute it via the terminal.

A variable declared in a function is a local variable. For example, the returnValue code below contains a local variable. By local variable we mean its meaning. I like Linux within this function, and we do not have access to this variable outside the body of the function. Regardless of the name of this function, the returnValue variable is given the value I like Linux.

# ! Function /bin/bash

{
returnValue=I like Linux

returnValue=I like MACecho $returningValueecho $returningValue

In this script you have a local function called funcCheck(). This function has a local returnValue variable with the value I love Linux. This return value is a local variable. After defining the function you see another declaration like returnValue=I like MAC, but this time it is a different variable than the one defined in the function. Save and run the script and you’ll see the difference.

14. Files and folders

In this topic you will learn how to create files and folders, how to check the existence of these files and folders using a script, how to read the text of files line by line, how to add text to files, and how to delete a file.

The first example script is to create a directory called Directory2. The mkdir directory creation command is used with the -p flag, which handles the error of creating the same directory or folder at a specific location.

Record this helloScript.sh. Open the terminal and execute the file. Then use ls -al to verify its existence.

#! /bin/bash
mkdir -p directory2

You can also use this .helloScript.sh to check whether or not a directory exists at your current location. Below is an example of a scenario for the implementation of this idea. The name of the folder must first be retrieved from the terminal. Read the line name of the terminal or folder and save it in any variable. Then use the operator as plus the flag -d, which checks whether the directory exists or not.

#! / Wastebasket / Basket

Enter a folder name to check the direct view

if [ -d $direct ]
, then
echo $direct
exists, otherwise
echo $direct does not exist
fi.

Save this ‘helloScript.sh’ file. Start it from the terminal and enter the phonebook name for the search.

Let’s get on with making the file. The touch command is used to create the file. The whole procedure for obtaining the name and reading the terminal is the same as for creating the directory, but to create the file you have to use the touch command instead of mkdir.

#! / Wastebasket/Bash

echo enter a file name to create
read file nameName

Touch $fileName

Save the script, execute it and check its existence via the terminal with the ls -al command.

You can also follow the script to search the folder, except for one small thing. Just replace the -d flag with -f because the -f flag searches for the file and the -d flag searches for folders.

#! / Wastebasket/Bash

echo Enter the file name to check
File name.

if [ -f $fileName ]
, then
echo $fileName
and
echo $fileName does not exist
fi.

To add text to a file, we must follow the same process. Step 1 – Get the file name from the terminal Step 2 – Look up this file when the program finds it and ask you to enter the text you want to add, otherwise print this file that is not in the terminal. If the program recognizes the file, t goes to the next step. Step 3 – read this text and write it to the desired file As you can see, all these steps are similar to the procedure for searching for documents, with the exception of the rule for adding. To add text to a file, simply write the following command ‘echo $fileText >> $fileName’ in your ‘helloScript.sh’.

#! / Wastebasket/Bash

echo enter the name of the file to which you want to add the text
read file name

if [ -f $fileName ]
, then
echo types the text you want to add
read fileText
echo $fileText >> $fileName
otherwise
echo $fileName does not exist
fi.

Run the file to see the results.

Now open the file to see if it works or not.

Restart the file and add a second time to be sure.

To replace the content of the file with the text you want to specify at runtime, simply use the ‘>’ symbol instead of ‘>>’ in the same script.

#! / Wastebasket/Bash

echo enter the name of the file to which you want to add the text
read file name

if [ -f $fileName ]
, then
echo types the text you want to add
read fileText
echo $fileText > $fileName
otherwise
echo $fileName does not exist
fi.

Save this helloScript.sh and execute the file in the terminal. You will see that the text has been replaced.

Open the file to see the changes.

You can also read any file using the script. Follow the method above to locate the file. Then use the while-condition to read the file with the read -r string. When we read the file, we see this symbol.

#! / Wastebasket/Bash

echo Enter the name of the file you want to read
Read file name

if [ -f $fileName ]
, then
, and IFS=read -r string
do
echo $line
done < $fileName
otherwise
echo $fileName does not exist
fi.

To delete a file, first check whether the file exists or not. Once you have found the file, use the rm command with the filename variable to delete it. To confirm the deletion, use ls -al to display the file system.

echo enter the name of the file from which you want to delete the read file name
.

if [ -f $fileName ]
, then
rm $fileName
otherwise
echo $fileName does not exist
fi

15. Send an e-mail via script

There are several methods to send emails through the shell, but we will use the simplest method. In order to work with e-mail, you must first define ssmtp.

You can first create a test email to understand the whole process. We have here a test e-mail [email protected]

Log in to your Google Account on the Security tab, select Access to less secure applications and save your settings.

The next step is editing the configuration file. Please follow the instructions below.

$ gedit /etc/ssmtp/ssmtp.conf

or…

sudo -H edited /etc/ssmtp/ssmtp.conf

Edit the following templates in ssmtp.conf

[email protected]
mailhub=sm.gmail.com:587
[email protected]
AuthPass= (you can enter your email password here)
UseSTARTTLS=yes

Now write the following lines of code into your helloScript.sh file.

#! /bin/bash
ssmtp [email protected]

Open the terminal and execute your helloScript.sh and define the structure of your email. Fill in the following information to send a test email to your account.

$ ./helloScript.sh

To:[email protected]
From:[email protected]
Cc:[email protected]
Subject:[email protected]
[email protected]

Go back to your email account and check your inbox.

How did you send yourself a test letter, it has to be in the things you sent, that makes sense, right?

16. ScenariosLoops

Roles are used to receive or send data files that may have a URL syntax. In order to process loops, you must first install the loop with the terminal.

After installing Curl, go back to your helloScript.sh and write the code to download the test file with the url. To download a data file with curls, you need to know two steps. The first is to have the full address of the link to this file. Next, you must save this address in the url variable of your script and load it with the curl command with this URL. Here, -O means it inherits its filename from its source.

#! /bin/bash
url=http://www.ovh.net/files/1Mb.dat
curl ${url} -O

To rename the uploaded file, simply use the -o flag and write the new filename as shown in the script below

#! /bin/bash
url=http://www.ovh.net/files/1Mb.dat
curl ${url} -o NewFileDownload

Save it in ‘helloScript.sh’, execute the file and you will see the following result.

What do you have to do if you want to download a file of several hundred gigabytes? Don’t you think it’s easier to know if you’re downloading the right file or not? In this case you can download the header file for confirmation. Put it in front of the url file. You will receive a file header from which you can choose whether or not to download the file.

#! /bin/bash
url=http://www.ovh.net/files/1Mb.dat
curl -I ${url}

Save the file and execute it with the command ./helloScript/sh, which gives the following result on the terminal

17. Menu for professionals

You will learn two things about this specific topic: first, how to manage the selection cycle and second, how to wait for the application.

In the first example, we create an auto menu in the script using the selection loop, and if you select one of the available options at runtime, that option is printed and the option you selected and the option you specified is displayed as input.

#! /bin/bash
select car in BMW MERCEDES TESLA ROVER TOYOTA
do
echo you select $car
done

Save the code in helloScript.sh and run the file to better understand how the selection cycle works.

In this case it will display the selected car option, but if you give it a number other than the options, it will do nothing. You can control this with the control box. Each case is used for one menu option, and if the user enters another vehicle option, an error message appears on the Choose between 1 and 5 screen.

# ! /bin/bash
select car in BMW MERCEDES TESLA ROVER TOYOTA
do
case $car in
BMW)
echo BMW SELECTED;;;;;
MERCEDES)
echo MERCEDES SELECTED ;
TESLA)
ultrasound TESLA SELECTED;;;;
ROVER)
ultrasound ROVER SELECTED;;;;
TOYOTA)
ultrasound TOYOTA SELECTED;;;;;
*)
ultrasound error ! Choose from 1 to 5;
esac
is ready.

Save the ‘helloScript.sh’ script and execute the file via the terminal.

In the professional menus, the program has to wait for the user to enter data. You can also write a scenario for this. In this scenario we ask the user to press any key to continue, then every three seconds we send a reminder with the command -t 3 -n 1, waiting for you to press the Sir key. In a different state, check whether or not the user has pressed a key. All these procedures are given below as examples. Save this ‘helloScript.sh’ file, open the terminal and execute it.

# ! /bin/bash
echo press any key to continue
while [ true ]

reads -t 3 -n 1
if [ $ ? = 0 ]
then
echo you have finished running script
;
another
echo is waiting for you to press sir
fi
done

18. Waiting for notified file system

This topic explains how to use inotify to wait for a file and make changes to it. inotify is essentially an inode notification. inotify is a subsystem of the Linux kernel that acts as a file system extension to detect changes in the file system and report those changes to applications. To work with inotify, you must first install inotify from the terminal.

sudo apt installs information tools

You can try to report in an imaginary catalogue to see how he will react. To do this, you need to write the following code into your helloScript.sh file.

#! /bin/bash
Wait -m /temp/ewFolder

Save the script, run it to compare the inotivation behavior with the imaginary file.

In the next section you can create a directory to test its functionality. Below you will find a sample code to perform this task in your script.

#! /bin/bash
mkdir -p temp/NewFolder
inotifywait -m temp/NewFolder

Save this script ‘helloScript.sh’, execute the file and you will see the following output on the terminal

Now open this file side by side while checking the output on the terminal.

Here you can see the applicant’s work as a monitor. If you open another terminal window and create a file in this folder with the touch command, you will see that inotify monitors all actions currently taking place on the file system.

Now try writing something in file1.text with another terminal window and check the answer from the terminal window that works with inotify.

19. Introduction to lubrication

Grep means global impression of regular expressions. This command is used to search for details in the file by processing the text line by line. We first create a file called filegrep.txt with the command key. Enter the following code into the terminal.

Open filegrep.txt and write in the following content.

This is Linux
This is Windows
This is MAC
This is Linux
This is Windows
This is MAC
This is Linux
This is Windows
This is MAC
This is Linux
This is Windows
This is MAC

Now go back to your helloScript.sh and we will re-use the file search code with some modifications according to the requirements of our current program. The main method of searching for files is described above in the section Files and Folders. The script first receives the file name of the user, then reads the input data, saves it in a variable and then asks the user to search for the text. It then reads the input data from the terminal, i.e. the text to be searched for in the file. The value is stored in another variable called handle bar. Now, the most important thing is to use the fingering command with the fingering variable and the filename. Ir will search the entire document for the word.

# ! /bin/bash
echo enter the file name to search for text from
, read fileName
as [[ -f $fileName ]].
then
echo type the text to search
read grepvar
grep $grepvar $fileName
otherwise
echo $fileName does not exist
fi

Save this .helloScript.sh script and execute it with the following command.

After the search procedure you can’t see anything because linux is entered and the text of the file Linux is written. Here you have to solve the problem of upper and lower case letters by simply adding the -i flag to the grep command.

grep -i $grepvar $fileName

Run the scenario again.

You can also retrieve the line number from the exit. Just add another -n flag to the fingering command.

grep -i -n $grepvar $fileName

Save the script and run the file through the terminal.

You can also find the number of times that word appears in the document. Add the ‘-c’ flag to the grep command ‘grep -i -c $grepvar $fileName’, save the script and execute it from the terminal.

You can also check different fingering commands by simply typing mangrep on the terminal.

20. Introduction to awk

Awk is a scripting language used to work with data and write reports. It requires no compilation and allows other users to use variables, numeric functions, string functions and logic operators. It can be seen as a tool that allows a programmer to write small but effective programs in the form of expressions that define the text patterns to be searched for in each line of the document and the action to be taken if a match is found in the line.

Can you ask what this seam is for? The idea is that awk transforms data files and also creates formatted reports. You can also use it to perform arithmetic and string operations, and to use conditioning operators and loops.

We will first scan the file line by line with the awk command. In this example you can also see the file search code, as it is needed to get the desired file. Then use the awk command with the print operation {print} and the filename variable.

# ! /bin/bash
echo enter the file name to print from awk
read fileName
as [[ -f $fileName ]].
, then
awk ‘{print}’ $fileName
otherwise
echo $fileName does not exist
fi

Register this .helloScript.sh and run it from the terminal.

Don’t worry about the filename filegrep.txt. It’s just a filename, and the name filgrep.txt doesn’t make it a grep file.

We can also use awk to search for a specific model. To do this, simply replace the above awk command with ‘awk ‘/Linux/ {print}” $fileName ‘. This script searches for Linux in the file and displays the lines it contains.

# ! /bin/bash
echo enters the file name to print awk
read fileName
as [[ -f $fileName ]].
, then

awk ‘/Linux/ {print}’ $fileName
otherwise
echo $fileName does not exist
fi

Now replace the content of filegrep.txt with the text below for new experiences.

It is Linux 2000Dies is Windows 3000Dies is MAC 4000Dies is Linux 2000Dies is Windows 3000Dies is MAC 4000Dies is Linux 2000Dies is Windows 3000Dies is MAC 4000Dies is MAC 4000.

The following example shows how to extract the content of the strings in which the program found its target word. The first word on this line is $1, the second $2, the third $3 and the last $4.

# ! /bin/bash
echo enter the file name to print from awk
read fileName
as [[ -f $fileName ]].
, then

awk ‘/Linux/ {print $2}’ $fileName
else
echo $fileName does not exist
fi

Save the above script and run the file to see if the second word is printed from the lines where the program found the word Linux.

Now run the script with the awk command to extract the last $4 word from the lines where it found Linux.

# ! /bin/bash
echo enters the file name to print awk
read fileName
as [[ -f $fileName ]].
, then

awk ‘/Linux/ {print $4} ‘ $fileName
else
echo $fileName does not exist
fi

Now use ‘awk’/Linux/ {print 3.4$}. The $fileName command to see if it works to print the second and last word of strings with Linux.

# ! /bin/bash
echo enters the file name to print awk
read fileName
as [[ -f $fileName ]].
, then

awk ‘/Linux/ {print $3.$4} ‘ $fileName
else
echo $fileName does not exist
fi

21. Introduction to the Limousine

The sed command refers to the flow editor, which performs edits to edit text from a standard input or file. sed edits in a linear, non-interactive way. This means that you make all processing decisions when you call up the order, and sed follows the instructions automatically. You learn to handle the limousine very easily. Use the same script we used for the previous task. We replace the I with the I. To do this, write the following command ‘cat filegrep.txt | sed ‘s/i/I/’, here the cat command is used to retrieve the contents of the file and after the pipe character ‘|’, with the keyword ‘sed’, we specify the operation that replaces this case. So it is an s with a slash and a letter to be replaced, then another slash and finally the last letter to be replaced.

# ! /bin/bash
echo enters file name for replacement by sed
read fileName
as [[ -f $fileName ]].
then
cat filegrep.txt | sed ‘s/i/I/’

otherwise
echo $fileName does not exist
fi

Save the script and run it from the terminal.

You can see on the output that only the first instance of i has been replaced by I. To replace i in all cases in the document, all you have to do is write g (which means global) after the last slash of /. Now save and run the script and you will see this change in all its content.

# ! /bin/bash
echo enters file name for replacement by sed
read fileName
as [[ -f $fileName ]].
then
cat filegrep.txt | sed ‘s/i/I/g’

otherwise
echo $fileName does not exist
fi

These changes will only be implemented at the time of implementation. You can also create another file to save the contents of the file displayed on the terminal by simply writing the following command in ‘helloScript.sh

cat filegrep.txt | sed ‘s/i/I/g’ > newfile.txt

You can also replace the whole word with another. For example, the script below replaces all cases of Linux with Unix when it is displayed on the terminal.

# ! /bin/bash
echo enters file name for replacement by sed
read fileName
as [[ -f $fileName ]].
then
sed ‘s/Linux/Unix/g’ $fileName

otherwise
echo $fileName does not exist
fi

22. Debugging bash scripts

Bash provides a complete debugging base. You can debug your hash script, and if something goes wrong, you can examine it. That’s what we do now. We’ll make a mistake on purpose to see what kind of mistake we’ll get in the terminal. Save the following code in the file helloScript.sh. Run the file through the terminal and check the result.

# ! /bin/bash
echo enters file name for replacement by sed
read fileName
as [[ -f $fileName ]].
than
sed ‘s/Linux/Unix/g’ $fileName

otherwise
echo $fileName does not exist
fi

You can tell by the error that it is present in the fourth line. But if you have thousands of lines of code and you come across many types of errors, it becomes so difficult to identify this thing. To do this, you can debug your script. The first method is step-by-step debugging using bash. To do this, simply write the following command into the terminal.

$ bash -x./helloScript.sh

Now run the script.

Just put the -x flag in the first line of the script after the basic path. With this method you debug your script.

# ! /bin/bash -x
echo enter file name for replacement by sed
read fileName
if [[ -f $fileName ]].
than
sed ‘s/Linux/Unix/g’ $fileName

otherwise
echo $fileName does not exist
fi

Allows you to select the starting and ending points for troubleshooting in the final method. At the beginning of debugging, write the command set -x, and to finish, just write set +x, save this helloScript.sh, run it in the terminal and check the results.

# ! /bin/bash
set -x
echo enter filename to replace with sed
read fileName
set +x
if [[ -f $fileName ]].
than
sed ‘s/Linux/Unix/g’ $fileName

otherwise
echo $fileName does not exist
fi

Look at the three-hour bathtub ride on YouTube:

Related Tags:

5900x 4k gaming,5950x vs 5900x benchmark,5900x vs 5950x reddit,5900x vs i9-10900k,5950x benchmark,5950x, ryzen,5900x msrp,ryzen 9 5950x benchmark,ryzen 9 5900x benchmark,ryzen 9 5900x vs 10900k,ryzen 9 5950x vs 10900k,ryzen 9 5900x price in india,ryzen processor,amd 3900x,amd ryzen 9 3900x,amd ryzen 9 3950x