-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShell_Scripting.txt
More file actions
406 lines (248 loc) · 11.3 KB
/
Shell_Scripting.txt
File metadata and controls
406 lines (248 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
link ---> https://www.freecodecamp.org/news/author/zaira/
How to define variables??
We can define a variable by using the syntax variable_name=value.
To get the value of the variable, add $ before the variable.
#!/bin/bash
# A simple variable example
greeting=Hello
name=Mahesh
echo $greeting $name
output: Hello Mahesh
*************************************************************************************
Arithmetic Expressions
Below are the operators supported by bash for mathematical calculations:
OPERATOR USAGE
+ addition
- subtraction
* multiplication
/ division
** exponentiation
% modulus
*************************************************************************************
How to read user input
Sometimes you'll need to gather user input and perform relevant operations.
In bash, we can take user input using the read command.
read variable_name
To prompt the user with a custom message, use the -p flag.
read -p "Enter your age" variable_name
Example:
#!/bin/bash
echo "Enter a numner"
read a
echo "Enter a numner"
read b
var=$((a+b))
echo $var
read -p "Enter first number: " a
read -p "Enter second number: " b
*************************************************************************************
Numeric Comparison logical operators
Comparison is used to check if statements evaluate to true or false. We can use the below shown operators to compare two statements:
OPERATION SYNTAX EXPLANATION
Equality num1 -eq num2 is num1 equal to num2
Greater than equal to num1 -ge num2 is num1 greater than equal to num2
Greater than num1 -gt num2 is num1 greater than num2
Less than equal to num1 -le num2 is num1 less than equal to num2
Less than num1 -lt num2 is num1 less than num2
Not Equal to num1 -ne num2 is num1 not equal to num2
Syntax:
if [ conditions ]
then
commands
fi
Example:
Let's compare two numbers and find their relationship:
read x
read y
if [ $x -gt $y ]
then
echo X is greater than Y
elif [ $x -lt $y ]
then
echo X is less than Y
elif [ $x -eq $y ]
then
echo X is equal to Y
fi
*************************************************************************************
Conditional Statements (Decision Making)
Conditions are expressions that evaluate to a boolean expression (true or false). To check conditions, we can use if, if-else, if-elif-else and nested conditionals.
The structure of conditional statements is as follows:
if...then...fi statements
if...then...else...fi statements
if..elif..else..fi
if..then..else..if..then..fi..fi.. (Nested Conditionals)
Syntax:
if [[ condition ]]
then
statement
elif [[ condition ]]; then
statement
else
do this by default
fi
To create meaningful comparisons, we can use AND -a and OR -o as well.
The below statement translates to: If a is greater than 40 and b is less than 6.
if [ $a -gt 40 -a $b -lt 6 ]
Example: Let's find the triangle type by reading the lengths of its sides.
read a
read b
read c
if [ $a == $b -a $b == $c -a $a == $c ]
then
echo EQUILATERAL
elif [ $a == $b -o $b == $c -o $a == $c ]
then
echo ISOSCELES
else
echo SCALENE
fi
*************************************************************************************
Looping and skipping
For loops allow you to execute statements a specific number of times.
Looping with numbers:
In the example below, the loop will iterate 5 times.
#!/bin/bash
for i in {1..5}
do
echo $i
done
*************************************************************************************
Looping with strings:
We can loop through strings as well.
#!/bin/bash
for X in cyan magenta yellow
do
echo $X
done
*************************************************************************************
While loop
While loops check for a condition and loop until the condition remains true. We need to provide a counter statement that increments the counter to control loop execution.
In the example below, (( i += 1 )) is the counter statement that increments the value of i.
Example:
#!/bin/bash
i=1
while [[ $i -le 10 ]] ; do
echo "$i"
(( i += 1 ))
done
*************************************************************************************
How to execute commands with back ticks
If you need to include the output of a complex command in your script, you can write the statement inside back ticks.
Syntax:
var= ` commands `
Example: Suppose we want to get the output of a list of mountpoints with tmpfs in their name. We can craft a statement like this: df -h | grep tmpfs.
To include it in the bash script, we can enclose it in back ticks.
#!/bin/bash
var=`df -h | grep tmpfs`
echo $var
*************************************************************************************
How to get arguments for scripts from the command line
It is possible to give arguments to the script on execution.
$@ represents the position of the parameters, starting from one.
#!/bin/bash
for x in $@
do
echo "Entered arg is $x"
done
*************************************************************************************
How to Automate Scripts by Scheduling via cron Jobs
Cron is a job scheduling utility present in Unix like systems. You can schedule jobs to execute daily, weekly, monthly or in a specific time of the day. Automation in Linux heavily relies on cron jobs.
Below is the syntax to schedule crons:
# Cron job example
* * * * * sh /path/to/script.sh
Here, * represent represents minute(s) hour(s) day(s) month(s) weekday(s), respectively.
Below are some examples of scheduling cron jobs.
SCHEDULE SCHEDULED VALUE
5 0 * 8 * At 00:05 in August.
5 4 * * 6 At 04:05 on Sunday.
0 22 * * 1-5 At 22:00 on every day-of-week from Monday through Friday.
*************************************************************************************
How to Check Existing Scripts in a System
Using crontab
crontab -l lists the already scheduled scripts for a particular user.
My scheduled scripts
*************************************************************************************
Using the find command
The find command helps to locate files based on certain patterns. As most of the scripts end with .sh, we can use the find script like this:
find . -type f -name "*.sh"
`
Where,
. represents the current directory. You can change the path accordingly.
-type f indicates that the file type we are looking for is a text based file.
*.sh tells to match all files ending with .sh.
Practical examples of find with bash scripts
We can combine find with rm or mv to create meaningful bash scripts that can be automated.
Let's say we want to create a script that moves log files older than 7 days to a backup path.
From there, it deletes log files older that older than 30 days.
We can create a script and schedule it with cron. You can learn more about cron jobs here.
Let's view the script:
#!/bin/bash
# Script to move from logs older than 7 days to backup logs path: /app/backup_logs/ESB0*
# move ESB01 logs to backup
find /logs/esb01/audit -name "*.tar.gz" -mtime +7 -exec mv {} app/backup_logs/ESB01/ \;
# Remove logs from backup path after 30 days
find /app/backup_logs/ESB01 -name "*.tar.gz" -mtime +30 -exec rm {} \;
Note that we are using exec with find. Basically, exec executes the command provided ( mv and rm in our case).
{} is the placeholder which holds the results of the command.
Lastly, we provide the delimiter ;.
As we do not want the shell to interpret the semicolon, we escape it with \.
*************************************************************************************
Grep command Tutorial
Grep Command in Linux – Usage, Options, and Syntax Examples
If you are a system admin who needs to scrape through log files or a developer trying to find certain occurrences in the code file,
then grep is a powerful command to use.
In this article, we will discuss the grep command's syntax and its usage with some examples.
Syntax of the grep Command
The syntax of the grep command is as follows:
grep [OPTION...] PATTERNS [FILE...]
Grep syntax
In the above syntax, grep searches for PATTERNS in each FILE. Grep finds each line that matched the provided PATTERN.
It is a good practice to close the PATTERN in quotes when grep is used in a shell command.
In this article, we will discuss the following options that can be used with grep:
-i, --ignore-case: Ignores case distinctions in patterns and input data.
-v, --invert-match: Selects the non-matching lines of the provided input pattern.
-n, --line-number: Prefix each line of the matching output with the line number in the input file.
-w: Find the exact matching word from the input file or string.
-c: Count the number of occurrences of the provided pattern.
In the coming examples, we will use the file fruits.txt with the following content:
apples and pears
citrus – oranges, grapefruits, mandarins and limes
stone fruit – nectarines, apricots, peaches and plums
tropical and exotic – bananas and mangoes
berries – strawBERRIES, raspberries, blueberries, kiwifruit and passionfruit
melons – watermelons, rockmelons and honeydew melons
tomatoes and avocados.
How to Find a Matching String with grep
If we want to find the string "fruit" in the file fruits.txt, we can do so like this:
grep "fruit" fruits.txt
How to Ignore Case Distinctions using -i
We can command grep to return results while ignoring the case of the matching string.
Let's find the word "berries" from our sample file. It should match all occurrences of "berries" regardless of their case.
grep -i "berries" fruits.txt
How to Select the Non-Matching Lines using -v
We can reverse the results of the grep command to include non-matching results. Let's say,
if we want to get all the lines that do not contain the word "berries", the command would look like this:
grep -v "berries" fruits.txt
The output returned all the lines that do not contain "berries".
How to Find the Line Numbers Against Matching Input using -n
There are times when we want to get the line numbers against the matching string. For that, we can supply the -n flag to grep like this:
grep -n "berries" fruits.txt
How to Find the Exact Matching Word from the Input File or String using -w
If you were to match an exact word rather than just the occurrence of a pattern, you can do so by using the -w flag.
If we grep "fruit" without any flags, it would return any occurrence of the word "fruit". This would include occurrences like "grapefruit", "dragonfruit" and so on like this:
image-77
But, if we only want "fruit" in our results, we can use the -w flag like this:
grep -w "fruit" fruits.txt
How to Count the Number of Occurrences of the Provided Pattern using -c
We can count the number of times the matched string appears in the file. This is how the -c flag works:
grep -c "fruit" fruits.txt
The word "fruit" appears 3 times in the file.
Tip: The -c flag can be very useful if you have to count the number of times an error message appeared in a log file.
How to Scan Files for Matching Input
Until now we had discussed how to search for matching patterns in a file or input string. We can also use grep to narrow down the files that contain a matching pattern. We can use the following flags to separate files that contain the matching pattern:
-l, --files-with-matches: Prints the file name that contains the provided matching pattern.
-L, --files-without-match: Prints the file name that does not contain the provided matching pattern.
Let's say we have the following files in our folder:
grep -l "echo" *.sh
grep -L "even" *.sh