-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathshell scripting notes
More file actions
581 lines (451 loc) · 10.7 KB
/
Copy pathshell scripting notes
File metadata and controls
581 lines (451 loc) · 10.7 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
shell script:
=============
-> to automate our compleate administration process
Introduction :
==============
shebang : #!
ex: #!/bin/bash, #!/bin/ksh
Comment: comments are not executable. comments are added using '#'
ex: # comment added
ex:
helloworld.sh
-------------
#!/bin/bash
# printing hello world
echo "Hello world!"
execution:
1. permissions : chmod +x helloworld.sh
2. ./helloworld.sh
Handling script arguments :
---------------------------
wish.sh
-------
#!/bin/bash
echo "Hello $1 $2 $3"
Ex: ./wish.sh Ramu Swapna Aishwarya
$0 --> wish.sh
$1 --> Ramu
$2 --> Swapna
$3 --> Aishwarya
1. $1,$2.... are used to refere 1st arg, 2nd arg ....etc
2. $0 refers name of the current script
3. args which are stored in $1 etc., are read only. we can't change from our script.
4. $@ --> all args provided (where all args can be treated one by one)
5. $# --> to count the amount of args provided
6. $* --> if you need a single string that contains all args (use in specific cases only)
Example :
#!/bin/bash
echo "Hello $1 $2"
Example arges 2 :
#!/bin/bash
echo "\$* gives $*"
echo "\$@ gives $@"
echo "\$# gives $#"
echo "\$0 gives $0"
for i in "$*"
do
echo $i
done
for j in "$@"
do
echo $j
done
exit 0
Pattern matching: (substitution operator or string operator )
=============================================================
Ex:
DATE=
echo ${DATE:-today}
echo ${DATE:=today}
echo ${DATE:?message}
DATE=$(date +%d-%m-%y)
echo date is ${DATE:0:2}
Reggular Expressions :c
======================
-> grep, cut, awk, sed etc are used for search patterns
Variables :
===========
we can declare variables using lowercase letters with underscore between words. EX: mission_name= lunar-mission
to access mission_name variable, echo $mission_name
Environment Variables:
======================
which are predefined variables in the shell. which uses all capital letters. EX: $PATH, $USER
Command line arguments :
========================
-> design our script to be reusable
-> script should not required to be edited before running
-> use command line arguments to pass inputs
Read Inputs :
==============
read -p "enter the mission name: " mission_name
Arithmatic operations in shell scripting :
==========================================
-> using expr command : expr 6 + 3, expr 6 \* 3
-> using double parenthsis : echo $((A+B)), echo $(( ++A ))
echo $((A/B)) | bc -l ---> for to get exact result in float point representation
Flow control :
==============
conditional logic :
--------------------
simple-if:
-----------
if [ somecondition ]
then
statement
fi
if-else:
--------
if [ somecondition ]
then
statement 1
elif [ some condition ]
statement 2
else
statement 3
fi
==> condition should be enclosed in square brackets '[]'
==> for strings only we should use '=' or '!=' operators
==> for other types, we can use '-eq, -ne, -lt, -gt'
==> example : if [ "abc" = "abc" ]
if [ 5 -gt 3 ]
==> in bash scripting., we can also use '[[ ... ]]' for to write conditions
==> examples in pattern management : [[ "abcd" = *bc* ]] --> abcd contains bc
[[ "abc" = ab[cd] ]] --> third character may be c or d
==> conditional operators : [ cond1 ] && [ cond2 ] or [[ cond1 && cond2 ]]
[ cond1 ] || [ cond2 ] or [[ cond1 || cond2 ]]
==> file level operators : [ -e FILE ] --> if file exists
[ -d FILE ] --> if file exists and it is dir
[ -s FILE ] --> if file exists and size greter than 0
[ -x FILE ] --> if file exists and it is executable
[ -w FILE ] --> if file exists and it is writable
*** example to check month number with month name :
================================================
#!/bin/bash
month_number=$1
if [ -z $month_number ]
then
echo "No month number given. Please enter a month number as a command line argument."
echo "eg: ./print-month-number 5"
exit
fi
if [[ $month_number -lt 1 ]] || [[ $month_number -gt 12 ]]
then
echo "Invalid month number given. Please enter a valid number - 1 to 12."
exit
fi
if [ $month_number -eq 1 ]
then
echo "January"
elif [ $month_number -eq 2 ]
then
echo "February"
elif [ $month_number -eq 3 ]
then
echo "March"
elif [ $month_number -eq 4 ]
then
echo "April"
elif [ $month_number -eq 5 ]
then
echo "May"
elif [ $month_number -eq 6 ]
then
echo "June"
elif [ $month_number -eq 7 ]
then
echo "July"
elif [ $month_number -eq 8 ]
then
echo "August"
elif [ $month_number -eq 9 ]
then
echo "September"
elif [ $month_number -eq 10 ]
then
echo "October"
elif [ $month_number -eq 11 ]
then
echo "November"
elif [ $month_number -eq 12 ]
then
echo December
fi
LOOPS :
=======
Array, List, Set ---> Group of elements
example: class=student1, student2, student3...
for student in student1 student2 .. student40; do
total_marks=
DRY(don't repeat yourself) code and WET(write everything twice) code
for:
----
syntax:
for mission in <--list of missions-->
do
command $mission
done
or
for mission in `cat mission-names.txt` --> $(cat mission-names.txt)
do
# command $mission
echo $mission
done
or
for (( mission = 0 ; mision <= 100 ; mission++ ))
do
echo $mission
done
==> execute a set commands multiple times
==> Iterate through files
==> Iterate through lines within a file
==> Iterate through the output of a command
Example1 :
for file in $(ls)
do
echo "Line count of $file is $(cat $file | wc -l )
done
Example2:
for server in $(cat servers.txt)
do
ssh $server "uptime"
done
Example3:
for package in $(install-packages.txt)
do
sudo apt-get -y install $package
done
Example4: Shell script to rename the images
for file in $(ls images)
do
if [[ $file = *.jpeg ]]
then
new_name=$(echo $file| sed 's/jpeg/jpg/g')
mv images/$file images/$new_name
fi
done
while loop :
============
==> Execute a command or a set of commands multiple times but we are not sure how many times.
==> Execute a command or a set of commands until a specific condition occurs
==> Create infine loops
==> Menu driven programs
Fibonacci series :
==================
0112358 13 21 ... --> fibonacci numbers
#!/bin/bash
x=0
y=1
i=2
echo "fibonacci series up to 1000 terms"
echo "$x"
echo "$y"
# -lt stands for equal to
while [ $i -lt 1000 ];
do
i=$(expr $i + 1)
z=$(expr $x + $y)
echo "$z"
x=$y
y=$z
done
Real time example 1:
--------------
while true
do
echo "1. Shutdown"
echo "2. Restart"
echo "3. Exit Menu"
read -p "Enter your choice: " choice
if [ $choice -eq 1 ]
then
shutdown now
elif [ $choice -eq 2 ]
then
shutdown -r now
elif [ $choice -eq 3 ]
then
break
else
continue
fi
done
Example 2:
----------
Break --> It stops iteration operation and come out from loop
Continue --> It stops current iteration and continues next iteration.
while true
do
echo "1. Add"
echo "2. Subtract"
echo "3. Multiply"
echo "4. Divide"
echo "5. Quit"
read -p "Enter your choice: " choice
if [ $choice -eq 1 ]
then
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
echo Answer=$(( $number1 + $number2 ))
elif [ $choice -eq 2 ]
then
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
echo Answer=$(( $number1 - $number2 ))
elif [ $choice -eq 3 ]
then
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
echo Answer=$(( $number1 * $number2 ))
elif [ $choice -eq 4 ]
then
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
echo Answer=$(( $number1 / $number2 ))
elif [ $choice -eq 5 ]
then
break
fi
done
case statement :
================
case syntax :
case VARIABLE in
1) statement1
;;
2) statement2
;;
.
.
.
esac
Example:
--------
while true
do
echo "1. Shutdown"
echo "2. Restart"
echo "3. Exit Menu"
read -p "Enter your choice: " choice
case $choice in
1) shutdown now
;;
2) shutdown -r now
;;
3) break
;;
4) continue
;;
esac
done
example 2:
----------
while true
do
echo "1. Add"
echo "2. Subtract"
echo "3. Multiply"
echo "4. Divide"
echo "5. Quit"
read -p "Enter your choice: " choice
case $choice in
1)
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
echo Answer=$(( $number1 + $number2 ))
;;
2)
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
echo Answer=$(( $number1 - $number2 ))
;;
3)
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
echo Answer=$(( $number1 * $number2 ))
;;
4)
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
echo Answer=$(( $number1 / $number2 ))
;;
5)
break
;;
esac
done
Shebang :
=========
For the best practice, It is good to use shebang ( #!/bin/bash ) before our script
Exit codes :
============
Exit code = 0 --> Sucess
Exit code > 1 (non-zero --> Failure
1 --> file not found
127 --> command not found
==> to see exit code : echo $?
==> It is best practice to use exit codes in our scripts.
Functions : To avoid duplication of code or in order to write DRY code. We use functions.
===========
Function defination :
function function_name() {
.
.
.
}
Function calling :
function_name <--args if any-->
==> We use return statement in function instead of exit statement
use cases:
----------
-> Break up large script that performs many tasks
-> Installing packages
-> Adding Users
-> Configuring firewalls
-> Perform mathematical calculations
Example 1 :
---------
function addition(){
echo $(( $1 + $2 ))
}
sum=$(addition 3 6)
Example 2 :
-----------
function addition(){
return $(( $1 + $2 ))
}
addition 3 6
sum=$?
Example 3 :
-----------
#!/bin/bash
function read_numbers(){
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
}
while true
do
echo "1. Add"
echo "2. Subtract"
echo "3. Multiply"
echo "4. Divide"
echo "5. Quit"
read -p "Enter your choice: " choice
case $choice in
1) read_numbers
echo $(( $number1 + $number2 )) ;;
2)
read_numbers
echo $(( $number1 - $number2 )) ;;
3)
read_numbers
echo $(( $number1 * $number2 )) ;;
4)
read_numbers
echo $(( $number1 / $number2 )) ;;
5) break
esac
done
Tips and tricks :
=================
1. install shellcheck utility through yum or apt-get (yum install -y shellcheck)
2. IDE's : IntelliJIdea, VSCode, Pycharm, Atom, Shell style guide