-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathshell-script.txt
More file actions
438 lines (327 loc) · 7.86 KB
/
shell-script.txt
File metadata and controls
438 lines (327 loc) · 7.86 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
==>.tn.txt
#!/bin/bash
#Simple Script
#Author:
echo $1 >> ~/notes.txt
echo $* >> ~/notes.txt
echo $(date): $* >> ~/notes.txt
echo $(date): $note >> ~/notes.txt
echo Note saved : $note
cmd line execute= './tn added date to note'
........................................
Shebang
- First line of file.
- Starts with #!.
- specify which interpreter should run the code.
- specify options for interpreter.
Bash Scripts
- #!/bin/bash
- don't name your script "test","if" or "ls".
type command:
- type test
.............................................
:~Variables~:
- a="Ram"
- echo $a
- files="file1 file2"
- touch $files
- ls -l $files
-Variable name letter,number and underscore.
-First character should be _ or letter.
-Case sensitive
*man
# Ask for input
read -p "your note: " note
-echo $date : $note >> ~/${topic}notes.txt
-echo Note saved: $note
////////////////////////////////////////////////////
#get the date
date = $(date)
#get the topic
topic=$1
#filename to write to
filename="${HOME}/${topic}notes.txt" #~/${topic}notes.txt
#ask user to read
read -p "your note: " note
echo "$date: $note" >> "$filename"
echo "Note \'$note\' saved to $filename"
/////////////////////////////////////////////////////
Good Habits:
- use "$x" instead of $x.
- prevent surprises when it contains spaces
- use double quotes : keeping meaning intact.
Debugging: set -x(enable) .... set +x(disable)
................................................................
::~If,Then,Else~::
if mkdir a;then echo "ok";else echo "error"; fi
if testcode;then
#code here gets executed
fi
if testcode;then
#code here gets executed
else
#some code
fi
////////////////////////////////////////////////////
#get the date
date = $(date)
#get the topic
topic=$1
#filename to write to
filename="${HOME}/${topic}notes.txt" #~/${topic}notes.txt
#ask user to read
read -p "your note: " note
if [[ $note ]];then
echo "$date: $note" >> "$filename"
echo "Note \'$note\' saved to $filename"
else
echo "Note wasn't saved"
fi
/////////////////////////////////////////////////////
return code or exit status
- value returned by program upon exit
- 0..255
- 0 means success other are error codes
conditional expression:
-tests on files and directories.
-tests on strings.
-arithmetic tests.
* [[ $str ]] str is not empty
[[ $str="something" ]] str equals to something
[[ -e $filename ]] file $filename exists
[[ -d $dirname ]] $dirname is a directory
Arithematic tests
[[arg1 op arg2]]
op:
-> -eq,-ne,-lt,-gt
-> $#,$?
if [[ $1 = "cat" ]];then
echo "meow"
elif [[ $1 = "dog" ]];then
echo "woof"
elif [[ $1 = "cow" ]];then
echo "mooo"
else
echo "unknown animal"
fi
-> && for and || for or ! for not
..................................................................
Inputs & Output
- Printf:
- more sophisticated output than echo.
- printf "hello\n".
- printf "hello %s, how are you\n"$USER
- printf "p%st\n" a e i o u
- printf "|%20s |%20s |%20s |\n" $(ls)
- For help: help printf, man printf
- read:
- reads input into a variable
- "read x"
- no variable specified? will use REPLY
- -n or -N number of chararcters to read
- -s will suppress output
- -r disallows escape seq, line continuation
- can splits into multiple varible
-read x y
-input "1 2 3"
read;echo $REPLY
//////////////////////////
#!/bin/bash
echo -n "Are you sure (Y/N)? "
answered=
while [[ ! $answered ]]; do
read -r -n 1 -s answer
if [[ $answer =[Yy] ]];then
answered="yes"
elif [[ $answer =[Nn] ]];then
answered="No"
fi
done
printf "\n%s\n" $answered
Standard Stream
- input,output,error
- Represented by number(file descriptor) or special file.
- 0: standard Input(stdin)
- 1: standard Output(stdout)
- 2: standard Error(stderr)
Redirection
- Input direction: <
- Output direction: >
- pipes ls | grep x
Redirection 2
- specific stream with N>
"cmd 2>dev/null" discards all errors
- specific stream with >&N
- sending both error and output to single file
cmd > logfile 2>&1
::~Control Flow~::
-Loops
-Break and continue
-case
-compound stmts
->while:
while test;do
code to repeat
done
->untill:
untill test;do
code to repeat
done
target=$(($Random % 100))
guess=
untill [[$guess -eq $target ]];do
read -p "Take a guess" guess
if [[$guess -lt $target]];then
echo "Higher!"
elif [[$guess -gt $target]];then
echo "Lower!"
else
echo "You found it!!"
fi
done
exit 0
->for
for var in words;do
//code to repeat
done
mvext::
if [[ $# -ne 2]];then
echo "you need exactly tow arguments"
fi
for i in *$1;do
base=$(basename "$f" "$1")
echo mv "$f" "#{base}$2"
done
touch {a..h}.txt
->for ((INIT;TEST;UPDATE));do
//loop code
done
->Break
->Continue
->case WORD in
PATTERN1)
code for pat1;;
PATTERN2)
code for pat1;;
.....
PATTERNN)
code for patn;;
esac
example::
case $1 in
cat)
echo "meow"
*)
echo "unknown animal"
esac
Command Groups
-> will group them in single stmt.
-> can use I/O redirection for whole group.
-> return status last command in group.
|| and &&
[[ $# -ne 2 ]] && { echo "need exactly two arguments" >&2;}// replacement for IF
::~Advance Variables~::
- integer variables
- declare -i num
num = "5+4"
echo $num #value 9
- let n=100/2
- ((p=x/100))
- ((p=$(ls|wc -l)*10))
declare -ir target = $(( ($RANDOM %100) + 1 ))
declare -i guess=0
untill ((guess == target));do
read -p "Take a guess: " guess
((guess)) || continue
if((guess < target ));then
echo "Higher!"
elif((guess > target ));then
echo "Lower!"
else
echo "You Found It!"
fi
done
declare -r var//constant variable
#exporting variables
- declare -x var="outer"
- export var
:_Arrays_:
storing value
-> x[0]="Ram"
retrive value
-> ${x[0]}
-> ${x[@]} or ${x[*]}
count no. of element in array=${#array[@]}
declare -A array
arr=(this is array)
declare -p arr
declare -a arr='([0]="this" [1]="is" [2]="an" [3]="array")'
:~Special Variables~:
- postional parameters
- holds the nth command line argument $1,$2...
- above 9 use braces : ${10}
- $0 holds script name
- $@ equivalent to $1,$2...,$N
- $* equivalent to $1,$2...,$N
- $# holds no. of arguments passed
Shift
- Remove the first argument
- All postional parameters shift
- $2 -> $1
- $# lowered by 1.
Getopts
-parse argument lists
-OPTARG,-OPTIND
::~Shell Functions~::
-Functions
-declare
-use
-return
-export
function name(){...}
sum(){
return $(( $1 + $2 ))
}
sum 4 5
echo $?
export function:: export -f fun
fun(){...}>&2 //function redirection
::-Fun With Strings-::
${var#pattern} #remove shortest possible match from begining.
${var##pattern} #remove longest possible match from begining.
${var%pattern} #remove shortest possible match from ending.
${var%%pattern} #remove longest possible match from ending.
${var/pattern/string} #search and replace
Default value
-> ${var:-value}
-> ${var-value}
-> ${var:=value}
-> =~ does RE matching
-> ? matches token 0 or 1 time.
-> * matches token any no. of times.
-> ^ matches token start of string.
-> $ matches token end of string.
::ENd of Options::
--
:--Many Ways to Run Your Script--:
- bash myscript
- bash -x myscript
- background running with &:: myscript &
- long-running script: nohup myscript &(keeping script running when you exit terminal)
- nice myscript(run in low pro=iority)
- nice nohup myscript &
=> tail -f logfile
- At:exec script at specific time
- cron: scheduling
:~Customize Bash Behaviour~:
-set: set -x print
-u
-n
-v
-e .... and more
-shopt: -s set,-u unset
shopt -s nocaseglob
extglob
dotglob
noclobber
.................................................................