├── .github
└── FUNDING.yml
└── README.md
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [idnan]
4 | custom: https://paypal.me/id9a9
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ## Table of Contents
6 | 1. [Basic Operations](#1-basic-operations)
7 | 1.1. [File Operations](#11-file-operations)
8 | 1.2. [Text Operations](#12-text-operations)
9 | 1.3. [Directory Operations](#13-directory-operations)
10 | 1.4. [SSH, System Info & Network Operations](#14-ssh-system-info--network-operations)
11 | 1.5. [Process Monitoring Operations](#15-process-monitoring-operations)
12 | 2. [Basic Shell Programming](#2-basic-shell-programming)
13 | 2.1. [Variables](#21-variables)
14 | 2.2. [Array](#22-array)
15 | 2.3. [String Substitution](#23-string-substitution)
16 | 2.4. [Functions](#24-functions)
17 | 2.5. [Conditionals](#25-conditionals)
18 | 2.6. [Loops](#26-loops)
19 | 3. [Tricks](#3-tricks)
20 | 4. [Debugging](#4-debugging)
21 |
22 |
23 | # 1. Basic Operations
24 |
25 | ### a. `export`
26 | Displays all environment variables. If you want to get details of a specific variable, use `echo $VARIABLE_NAME`.
27 | ```bash
28 | export
29 | ```
30 | Example:
31 | ```bash
32 | $ export
33 | AWS_HOME=/Users/adnanadnan/.aws
34 | LANG=en_US.UTF-8
35 | LC_CTYPE=en_US.UTF-8
36 | LESS=-R
37 |
38 | $ echo $AWS_HOME
39 | /Users/adnanadnan/.aws
40 | ```
41 |
42 | ### b. `whatis`
43 | whatis shows description for user commands, system calls, library functions, and others in manual pages
44 | ```bash
45 | whatis something
46 | ```
47 | Example:
48 | ```bash
49 | $ whatis bash
50 | bash (1) - GNU Bourne-Again SHell
51 | ```
52 |
53 | ### c. `whereis`
54 | whereis searches for executables, source files, and manual pages using a database built by system automatically.
55 | ```bash
56 | whereis name
57 | ```
58 | Example:
59 | ```bash
60 | $ whereis php
61 | /usr/bin/php
62 | ```
63 |
64 | ### d. `which`
65 | which searches for executables in the directories specified by the environment variable PATH. This command will print the full path of the executable(s).
66 | ```bash
67 | which program_name
68 | ```
69 | Example:
70 | ```bash
71 | $ which php
72 | /c/xampp/php/php
73 | ```
74 |
75 | ### e. clear
76 | Clears content on window.
77 |
78 | ## 1.1. File Operations
79 |
105 |
106 | ### a. `cat`
107 | It can be used for the following purposes under UNIX or Linux.
108 | * Display text files on screen
109 | * Copy text files
110 | * Combine text files
111 | * Create new text files
112 | ```bash
113 | cat filename
114 | cat file1 file2
115 | cat file1 file2 > newcombinedfile
116 | cat < file1 > file2 #copy file1 to file2
117 | ```
118 |
119 | ### b. `chmod`
120 | The chmod command stands for "change mode" and allows you to change the read, write, and execute permissions on your files and folders. For more information on this command check this [link](https://ss64.com/bash/chmod.html).
121 | ```bash
122 | chmod -options filename
123 | ```
124 |
125 | ### c. `chown`
126 | The chown command stands for "change owner", and allows you to change the owner of a given file or folder, which can be a user and a group. Basic usage is simple forward first comes the user (owner), and then the group, delimited by a colon.
127 | ```bash
128 | chown -options user:group filename
129 | ```
130 |
131 | ### d. `cp`
132 | Copies a file from one location to other.
133 | ```bash
134 | cp filename1 filename2
135 | ```
136 | Where `filename1` is the source path to the file and `filename2` is the destination path to the file.
137 |
138 | ### e. `diff`
139 | Compares files, and lists their differences.
140 | ```bash
141 | diff filename1 filename2
142 | ```
143 |
144 | ### f. `file`
145 | Determine file type.
146 | ```bash
147 | file filename
148 | ```
149 | Example:
150 | ```bash
151 | $ file index.html
152 | index.html: HTML document, ASCII text
153 | ```
154 | ### g. `find`
155 | Find files in directory
156 | ```bash
157 | find directory options pattern
158 | ```
159 | Example:
160 | ```bash
161 | $ find . -name README.md
162 | $ find /home/user1 -name '*.png'
163 | ```
164 |
165 | ### h. `gunzip`
166 | Un-compresses files compressed by gzip.
167 | ```bash
168 | gunzip filename
169 | ```
170 |
171 | ### i. `gzcat`
172 | Lets you look at gzipped file without actually having to gunzip it.
173 | ```bash
174 | gzcat filename
175 | ```
176 |
177 | ### j. `gzip`
178 | Compresses files.
179 | ```bash
180 | gzip filename
181 | ```
182 |
183 | ### k. `head`
184 | Outputs the first 10 lines of file
185 | ```bash
186 | head filename
187 | ```
188 |
189 | ### l. `lpq`
190 | Check out the printer queue.
191 | ```bash
192 | lpq
193 | ```
194 | Example:
195 | ```bash
196 | $ lpq
197 | Rank Owner Job File(s) Total Size
198 | active adnanad 59 demo 399360 bytes
199 | 1st adnanad 60 (stdin) 0 bytes
200 | ```
201 |
202 | ### m. `lpr`
203 | Print the file.
204 | ```bash
205 | lpr filename
206 | ```
207 |
208 | ### n. `lprm`
209 | Remove something from the printer queue.
210 | ```bash
211 | lprm jobnumber
212 | ```
213 |
214 | ### o. `ls`
215 | Lists your files. `ls` has many options: `-l` lists files in 'long format', which contains the exact size of the file, who owns the file, who has the right to look at it, and when it was last modified. `-a` lists all files, including hidden files. For more information on this command check this [link](https://ss64.com/bash/ls.html).
216 | ```bash
217 | ls option
218 | ```
219 | Example:
220 |
221 | $ ls -la
222 | rwxr-xr-x 33 adnan staff 1122 Mar 27 18:44 .
223 | drwxrwxrwx 60 adnan staff 2040 Mar 21 15:06 ..
224 | -rw-r--r--@ 1 adnan staff 14340 Mar 23 15:05 .DS_Store
225 | -rw-r--r-- 1 adnan staff 157 Mar 25 18:08 .bumpversion.cfg
226 | -rw-r--r-- 1 adnan staff 6515 Mar 25 18:08 .config.ini
227 | -rw-r--r-- 1 adnan staff 5805 Mar 27 18:44 .config.override.ini
228 | drwxr-xr-x 17 adnan staff 578 Mar 27 23:36 .git
229 | -rwxr-xr-x 1 adnan staff 2702 Mar 25 18:08 .gitignore
230 |
231 |
232 | ### p. `more`
233 | Shows the first part of a file (move with space and type q to quit).
234 | ```bash
235 | more filename
236 | ```
237 |
238 | ### q. `mv`
239 | Moves a file from one location to other.
240 | ```bash
241 | mv filename1 filename2
242 | ```
243 | Where `filename1` is the source path to the file and `filename2` is the destination path to the file.
244 |
245 | Also it can be used for rename a file.
246 | ```bash
247 | mv old_name new_name
248 | ```
249 |
250 | ### r. `rm`
251 | Removes a file. Using this command on a directory gives you an error.
252 | `rm: directory: is a directory`
253 | To remove a directory you have to pass `-r` which will remove the content of the directory recursively. Optionally you can use `-f` flag to force the deletion i.e. without any confirmations etc.
254 | ```bash
255 | rm filename
256 | ```
257 |
258 | ### s. `tail`
259 | Outputs the last 10 lines of file. Use `-f` to output appended data as the file grows.
260 | ```bash
261 | tail filename
262 | ```
263 |
264 | ### t. `touch`
265 | Updates access and modification time stamps of your file. If it doesn't exists, it'll be created.
266 | ```bash
267 | touch filename
268 | ```
269 | Example:
270 | ```bash
271 | $ touch trick.md
272 | ```
273 |
274 | ## 1.2. Text Operations
275 |
276 |
295 |
296 | ### a. `awk`
297 | awk is the most useful command for handling text files. It operates on an entire file line by line. By default it uses whitespace to separate the fields. The most common syntax for awk command is
298 |
299 | ```bash
300 | awk '/search_pattern/ { action_to_take_if_pattern_matches; }' file_to_parse
301 | ```
302 |
303 | Lets take following file `/etc/passwd`. Here's the sample data that this file contains:
304 | ```
305 | root:x:0:0:root:/root:/usr/bin/zsh
306 | daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
307 | bin:x:2:2:bin:/bin:/usr/sbin/nologin
308 | sys:x:3:3:sys:/dev:/usr/sbin/nologin
309 | sync:x:4:65534:sync:/bin:/bin/sync
310 | ```
311 | So now lets get only username from this file. Where `-F` specifies that on which base we are going to separate the fields. In our case it's `:`. `{ print $1 }` means print out the first matching field.
312 | ```bash
313 | awk -F':' '{ print $1 }' /etc/passwd
314 | ```
315 | After running the above command you will get following output.
316 | ```
317 | root
318 | daemon
319 | bin
320 | sys
321 | sync
322 | ```
323 | For more detail on how to use `awk`, check following [link](https://www.cyberciti.biz/faq/bash-scripting-using-awk).
324 |
325 |
326 | ### b. `cut`
327 | Remove sections from each line of files
328 |
329 | *example.txt*
330 | ```bash
331 | red riding hood went to the park to play
332 | ```
333 |
334 | *show me columns 2 , 7 , and 9 with a space as a separator*
335 | ```bash
336 | cut -d " " -f2,7,9 example.txt
337 | ```
338 | ```bash
339 | riding park play
340 | ```
341 |
342 | ### c. `echo`
343 | Display a line of text
344 |
345 | *display "Hello World"*
346 | ```bash
347 | echo Hello World
348 | ```
349 | ```bash
350 | Hello World
351 | ```
352 |
353 | *display "Hello World" with newlines between words*
354 | ```bash
355 | echo -ne "Hello\nWorld\n"
356 | ```
357 | ```bash
358 | Hello
359 | World
360 | ```
361 |
362 | ### d. `egrep`
363 | Print lines matching a pattern - Extended Expression (alias for: 'grep -E')
364 |
365 | *example.txt*
366 | ```bash
367 | Lorem ipsum
368 | dolor sit amet,
369 | consetetur
370 | sadipscing elitr,
371 | sed diam nonumy
372 | eirmod tempor
373 | invidunt ut labore
374 | et dolore magna
375 | aliquyam erat, sed
376 | diam voluptua. At
377 | vero eos et
378 | accusam et justo
379 | duo dolores et ea
380 | rebum. Stet clita
381 | kasd gubergren,
382 | no sea takimata
383 | sanctus est Lorem
384 | ipsum dolor sit
385 | amet.
386 | ```
387 |
388 | *display lines that have either "Lorem" or "dolor" in them.*
389 | ```bash
390 | egrep '(Lorem|dolor)' example.txt
391 | or
392 | grep -E '(Lorem|dolor)' example.txt
393 | ```
394 | ```bash
395 | Lorem ipsum
396 | dolor sit amet,
397 | et dolore magna
398 | duo dolores et ea
399 | sanctus est Lorem
400 | ipsum dolor sit
401 | ```
402 |
403 | ### e. `fgrep`
404 | Print lines matching a pattern - FIXED pattern matching (alias for: 'grep -F')
405 |
406 | *example.txt*
407 | ```bash
408 | Lorem ipsum
409 | dolor sit amet,
410 | consetetur
411 | sadipscing elitr,
412 | sed diam nonumy
413 | eirmod tempor
414 | foo (Lorem|dolor)
415 | invidunt ut labore
416 | et dolore magna
417 | aliquyam erat, sed
418 | diam voluptua. At
419 | vero eos et
420 | accusam et justo
421 | duo dolores et ea
422 | rebum. Stet clita
423 | kasd gubergren,
424 | no sea takimata
425 | sanctus est Lorem
426 | ipsum dolor sit
427 | amet.
428 | ```
429 |
430 | *Find the exact string '(Lorem|dolor)' in example.txt*
431 | ```bash
432 | fgrep '(Lorem|dolor)' example.txt
433 | or
434 | grep -F '(Lorem|dolor)' example.txt
435 | ```
436 | ```bash
437 | foo (Lorem|dolor)
438 | ```
439 |
440 | ### f. `fmt`
441 | Simple optimal text formatter
442 |
443 | *example: example.txt (1 line)*
444 | ```bash
445 | Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
446 | ```
447 |
448 | *output the lines of example.txt to 20 character width*
449 | ```bash
450 | cat example.txt | fmt -w 20
451 | ```
452 | ```bash
453 | Lorem ipsum
454 | dolor sit amet,
455 | consetetur
456 | sadipscing elitr,
457 | sed diam nonumy
458 | eirmod tempor
459 | invidunt ut labore
460 | et dolore magna
461 | aliquyam erat, sed
462 | diam voluptua. At
463 | vero eos et
464 | accusam et justo
465 | duo dolores et ea
466 | rebum. Stet clita
467 | kasd gubergren,
468 | no sea takimata
469 | sanctus est Lorem
470 | ipsum dolor sit
471 | amet.
472 | ```
473 |
474 | ### g. `grep`
475 | Looks for text inside files. You can use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines.
476 | ```bash
477 | grep pattern filename
478 | ```
479 | Example:
480 | ```bash
481 | $ grep admin /etc/passwd
482 | _kadmin_admin:*:218:-2:Kerberos Admin Service:/var/empty:/usr/bin/false
483 | _kadmin_changepw:*:219:-2:Kerberos Change Password Service:/var/empty:/usr/bin/false
484 | _krb_kadmin:*:231:-2:Open Directory Kerberos Admin Service:/var/empty:/usr/bin/false
485 | ```
486 | You can also force grep to ignore word case by using `-i` option. `-r` can be used to search all files under the specified directory, for example:
487 | ```bash
488 | $ grep -r admin /etc/
489 | ```
490 | And `-w` to search for words only. For more detail on `grep`, check following [link](https://www.cyberciti.biz/faq/grep-in-bash).
491 |
492 | ### h. `nl`
493 | Number lines of files
494 |
495 | *example.txt*
496 | ```bash
497 | Lorem ipsum
498 | dolor sit amet,
499 | consetetur
500 | sadipscing elitr,
501 | sed diam nonumy
502 | eirmod tempor
503 | invidunt ut labore
504 | et dolore magna
505 | aliquyam erat, sed
506 | diam voluptua. At
507 | vero eos et
508 | accusam et justo
509 | duo dolores et ea
510 | rebum. Stet clita
511 | kasd gubergren,
512 | no sea takimata
513 | sanctus est Lorem
514 | ipsum dolor sit
515 | amet.
516 | ```
517 |
518 | *show example.txt with line numbers*
519 | ```bash
520 | nl -s". " example.txt
521 | ```
522 | ```bash
523 | 1. Lorem ipsum
524 | 2. dolor sit amet,
525 | 3. consetetur
526 | 4. sadipscing elitr,
527 | 5. sed diam nonumy
528 | 6. eirmod tempor
529 | 7. invidunt ut labore
530 | 8. et dolore magna
531 | 9. aliquyam erat, sed
532 | 10. diam voluptua. At
533 | 11. vero eos et
534 | 12. accusam et justo
535 | 13. duo dolores et ea
536 | 14. rebum. Stet clita
537 | 15. kasd gubergren,
538 | 16. no sea takimata
539 | 17. sanctus est Lorem
540 | 18. ipsum dolor sit
541 | 19. amet.
542 | ```
543 |
544 | ### i. `sed`
545 | Stream editor for filtering and transforming text
546 |
547 | *example.txt*
548 | ```bash
549 | Hello This is a Test 1 2 3 4
550 | ```
551 |
552 | *replace all spaces with hyphens*
553 | ```bash
554 | sed 's/ /-/g' example.txt
555 | ```
556 | ```bash
557 | Hello-This-is-a-Test-1-2-3-4
558 | ```
559 |
560 | *replace all digits with "d"*
561 | ```bash
562 | sed 's/[0-9]/d/g' example.txt
563 | ```
564 | ```bash
565 | Hello This is a Test d d d d
566 | ```
567 |
568 | ### j. `sort`
569 | Sort lines of text files
570 |
571 | *example.txt*
572 | ```bash
573 | f
574 | b
575 | c
576 | g
577 | a
578 | e
579 | d
580 | ```
581 |
582 | *sort example.txt*
583 | ```bash
584 | sort example.txt
585 | ```
586 | ```bash
587 | a
588 | b
589 | c
590 | d
591 | e
592 | f
593 | g
594 | ```
595 |
596 | *randomize a sorted example.txt*
597 | ```bash
598 | sort example.txt | sort -R
599 | ```
600 | ```bash
601 | b
602 | f
603 | a
604 | c
605 | d
606 | g
607 | e
608 | ```
609 |
610 | ### k. `tr`
611 | Translate or delete characters
612 |
613 | *example.txt*
614 | ```bash
615 | Hello World Foo Bar Baz!
616 | ```
617 |
618 | *take all lower case letters and make them upper case*
619 | ```bash
620 | cat example.txt | tr 'a-z' 'A-Z'
621 | ```
622 | ```bash
623 | HELLO WORLD FOO BAR BAZ!
624 | ```
625 |
626 | *take all spaces and make them into newlines*
627 | ```bash
628 | cat example.txt | tr ' ' '\n'
629 | ```
630 | ```bash
631 | Hello
632 | World
633 | Foo
634 | Bar
635 | Baz!
636 | ```
637 |
638 | ### l. `uniq`
639 | Report or omit repeated lines
640 |
641 | *example.txt*
642 | ```bash
643 | a
644 | a
645 | b
646 | a
647 | b
648 | c
649 | d
650 | c
651 | ```
652 |
653 | *show only unique lines of example.txt (first you need to sort it, otherwise it won't see the overlap)*
654 | ```bash
655 | sort example.txt | uniq
656 | ```
657 | ```bash
658 | a
659 | b
660 | c
661 | d
662 | ```
663 |
664 | *show the unique items for each line, and tell me how many instances it found*
665 | ```bash
666 | sort example.txt | uniq -c
667 | ```
668 | ```bash
669 | 3 a
670 | 2 b
671 | 2 c
672 | 1 d
673 | ```
674 |
675 | ### m. `wc`
676 | Tells you how many lines, words and characters there are in a file.
677 | ```bash
678 | wc filename
679 | ```
680 | Example:
681 | ```bash
682 | $ wc demo.txt
683 | 7459 15915 398400 demo.txt
684 | ```
685 | Where `7459` is lines, `15915` is words and `398400` is characters.
686 |
687 | ## 1.3. Directory Operations
688 |
689 |
696 |
697 | ### a. `cd`
698 | Moves you from one directory to other. Running this
699 | ```bash
700 | $ cd
701 | ```
702 | moves you to home directory. This command accepts an optional `dirname`, which moves you to that directory.
703 | ```bash
704 | cd dirname
705 | ```
706 |
707 | ### b. `mkdir`
708 | Makes a new directory.
709 | ```bash
710 | mkdir dirname
711 | ```
712 | You can use this to create multiple directories at once within your current directory.
713 | ```bash
714 | mkdir 1stDirectory 2ndDirectory 3rdDirectory
715 | ```
716 | You can also use this to create parent directories at the same time. For instance, if you wanted a directory named 'project1' in another subdirectory at '/samples/bash/projects/', you could run:
717 | ```bash
718 | mkdir /samples/bash/projects/project1
719 | ```
720 | If any of these directories did no already exist, they would be created as well.
721 |
722 | ### c. `pwd`
723 | Tells you which directory you currently are in.
724 | ```bash
725 | pwd
726 | ```
727 |
728 | ## 1.4. SSH, System Info & Network Operations
729 |
730 |
762 |
763 | ### a. `bg`
764 | Lists stopped or background jobs; resume a stopped job in the background.
765 |
766 | ### b. `cal`
767 | Shows the month's calendar.
768 |
769 | ### c. `date`
770 | Shows the current date and time.
771 |
772 | ### d. `df`
773 | Shows disk usage.
774 |
775 | ### e. `dig`
776 | Gets DNS information for domain.
777 | ```bash
778 | dig domain
779 | ```
780 |
781 | ### f. `du`
782 | Shows the disk usage of files or directories. For more information on this command check this [link](http://www.linfo.org/du.html)
783 | ```bash
784 | du [option] [filename|directory]
785 | ```
786 | Options:
787 | - `-h` (human readable) Displays output it in kilobytes (K), megabytes (M) and gigabytes (G).
788 | - `-s` (supress or summarize) Outputs total disk space of a directory and supresses reports for subdirectories.
789 |
790 | Example:
791 | ```bash
792 | du -sh pictures
793 | 1.4M pictures
794 | ```
795 |
796 | ### g. `fg`
797 | Brings the most recent job in the foreground.
798 |
799 | ### h. `finger`
800 | Displays information about user.
801 | ```bash
802 | finger username
803 | ```
804 | ### i. `jobs`
805 | Lists the jobs running in the background, giving the job number.
806 |
807 | ### j. `last`
808 | Lists your last logins of specified user.
809 | ```bash
810 | last yourUsername
811 | ```
812 |
813 | ### k. `man`
814 | Shows the manual for specified command.
815 | ```bash
816 | man command
817 | ```
818 |
819 | ### l. `passwd`
820 | Allows the current logged user to change their password.
821 |
822 | ### m. `ping`
823 | Pings host and outputs results.
824 | ```bash
825 | ping host
826 | ```
827 |
828 | ### n. `ps`
829 | Lists your processes.
830 | ```bash
831 | ps -u yourusername
832 | ```
833 | Use the flags ef. e for every process and f for full listing.
834 | ```bash
835 | ps -ef
836 | ```
837 |
838 | ### o. `quota`
839 | Shows what your disk quota is.
840 | ```bash
841 | quota -v
842 | ```
843 |
844 | ### p. `scp`
845 | Transfer files between a local host and a remote host or between two remote hosts.
846 |
847 | *copy from local host to remote host*
848 | ```bash
849 | scp source_file user@host:directory/target_file
850 | ```
851 | *copy from remote host to local host*
852 | ```bash
853 | scp user@host:directory/source_file target_file
854 | scp -r user@host:directory/source_folder target_folder
855 | ```
856 | This command also accepts an option `-P` that can be used to connect to specific port.
857 | ```bash
858 | scp -P port user@host:directory/source_file target_file
859 | ```
860 |
861 | ### q. `ssh`
862 | ssh (SSH client) is a program for logging into and executing commands on a remote machine.
863 | ```bash
864 | ssh user@host
865 | ```
866 | This command also accepts an option `-p` that can be used to connect to specific port.
867 | ```bash
868 | ssh -p port user@host
869 | ```
870 |
871 | ### r. `top`
872 | Displays your currently active processes.
873 |
874 | ### s. `uname`
875 | Shows kernel information.
876 | ```bash
877 | uname -a
878 | ```
879 |
880 | ### t. `uptime`
881 | Shows current uptime.
882 |
883 | ### u. `w`
884 | Displays who is online.
885 |
886 | ### v. `wget`
887 | Downloads file.
888 | ```bash
889 | wget file
890 | ```
891 |
892 | ### w. `whoami`
893 | Return current logged in username.
894 |
895 | ### x. `whois`
896 | Gets whois information for domain.
897 | ```bash
898 | whois domain
899 | ```
900 |
901 | ## 1.5. Process Monitoring Operations
902 |
903 |
911 |
912 | ### a. `kill`
913 | Kills (ends) the processes with the ID you gave.
914 | ```bash
915 | kill PID
916 | ```
917 |
918 | ### b. `killall`
919 | Kill all processes with the name.
920 | ```bash
921 | killall processname
922 | ```
923 |
924 | ### c. &
925 | The `&` symbol instructs the command to run as a background process in a subshell.
926 | ```bash
927 | command &
928 | ```
929 |
930 | ### d. `nohup`
931 | nohup stands for "No Hang Up". This allows to run command/process or shell script that can continue running in the background after you log out from a shell.
932 | ```bash
933 | nohup command
934 | ```
935 | Combine it with `&` to create background processes
936 | ```bash
937 | nohup command &
938 | ```
939 |
940 | # 2. Basic Shell Programming
941 |
942 |
943 | The first line that you will write in bash script files is called `shebang`. This line in any script determines the script's ability to be executed like a standalone executable without typing sh, bash, python, php etc beforehand in the terminal.
944 |
945 | ```bash
946 | #!/usr/bin/env bash
947 | ```
948 |
949 | ## 2.1. Variables
950 |
951 | Creating variables in bash is similar to other languages. There are no data types. A variable in bash can contain a number, a character, a string of characters, etc. You have no need to declare a variable, just assigning a value to its reference will create it.
952 |
953 | Example:
954 | ```bash
955 | str="hello world"
956 | ```
957 |
958 | The above line creates a variable `str` and assigns "hello world" to it. The value of variable is retrieved by putting the `$` in the beginning of variable name.
959 |
960 | Example:
961 | ```bash
962 | echo $str # hello world
963 | ```
964 | ## 2.2. Array
965 | Like other languages bash has also arrays. An array is a variable containing multiple values. There's no maximum limit on the size of array. Arrays in bash are zero based. The first element is indexed with element 0. There are several ways for creating arrays in bash which are given below.
966 |
967 | Examples:
968 | ```bash
969 | array[0]=val
970 | array[1]=val
971 | array[2]=val
972 | array=([2]=val [0]=val [1]=val)
973 | array=(val val val)
974 | ```
975 | To display a value at specific index use following syntax:
976 |
977 | ```bash
978 | ${array[i]} # where i is the index
979 | ```
980 |
981 | If no index is supplied, array element 0 is assumed. To find out how many values there are in the array use the following syntax:
982 |
983 | ```bash
984 | ${#array[@]}
985 | ```
986 |
987 | Bash has also support for the ternary conditions. Check some examples below.
988 |
989 | ```bash
990 | ${varname:-word} # if varname exists and isn't null, return its value; otherwise return word
991 | ${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value
992 | ${varname:+word} # if varname exists and isn't null, return word; otherwise return null
993 | ${varname:offset:length} # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters
994 | ```
995 |
996 | ## 2.3 String Substitution
997 |
998 | Check some of the syntax on how to manipulate strings
999 |
1000 | ```bash
1001 | ${variable#pattern} # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest
1002 | ${variable##pattern} # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest
1003 | ${variable%pattern} # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest
1004 | ${variable%%pattern} # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest
1005 | ${variable/pattern/string} # the longest match to pattern in variable is replaced by string. Only the first match is replaced
1006 | ${variable//pattern/string} # the longest match to pattern in variable is replaced by string. All matches are replaced
1007 | ${#varname} # returns the length of the value of the variable as a character string
1008 | ```
1009 |
1010 | ## 2.4. Functions
1011 | As in almost any programming language, you can use functions to group pieces of code in a more logical way or practice the divine art of recursion. Declaring a function is just a matter of writing function my_func { my_code }. Calling a function is just like calling another program, you just write its name.
1012 |
1013 | ```bash
1014 | function name() {
1015 | shell commands
1016 | }
1017 | ```
1018 |
1019 | Example:
1020 | ```bash
1021 | #!/bin/bash
1022 | function hello {
1023 | echo world!
1024 | }
1025 | hello
1026 |
1027 | function say {
1028 | echo $1
1029 | }
1030 | say "hello world!"
1031 | ```
1032 |
1033 | When you run the above example the `hello` function will output "world!". The above two functions `hello` and `say` are identical. The main difference is function `say`. This function, prints the first argument it receives. Arguments, within functions, are treated in the same manner as arguments given to the script.
1034 |
1035 | ## 2.5. Conditionals
1036 |
1037 | The conditional statement in bash is similar to other programming languages. Conditions have many form like the most basic form is `if` expression `then` statement where statement is only executed if expression is true.
1038 |
1039 | ```bash
1040 | if [ expression ]; then
1041 | will execute only if expression is true
1042 | else
1043 | will execute if expression is false
1044 | fi
1045 | ```
1046 |
1047 | Sometime if conditions becoming confusing so you can write the same condition using the `case statements`.
1048 |
1049 | ```bash
1050 | case expression in
1051 | pattern1 )
1052 | statements ;;
1053 | pattern2 )
1054 | statements ;;
1055 | ...
1056 | esac
1057 | ```
1058 |
1059 | Expression Examples:
1060 |
1061 | ```bash
1062 | statement1 && statement2 # both statements are true
1063 | statement1 || statement2 # at least one of the statements is true
1064 |
1065 | str1=str2 # str1 matches str2
1066 | str1!=str2 # str1 does not match str2
1067 | str1str2 # str1 is greater than str2
1069 | -n str1 # str1 is not null (has length greater than 0)
1070 | -z str1 # str1 is null (has length 0)
1071 |
1072 | -a file # file exists
1073 | -d file # file exists and is a directory
1074 | -e file # file exists; same -a
1075 | -f file # file exists and is a regular file (i.e., not a directory or other special type of file)
1076 | -r file # you have read permission
1077 | -s file # file exists and is not empty
1078 | -w file # you have write permission
1079 | -x file # you have execute permission on file, or directory search permission if it is a directory
1080 | -N file # file was modified since it was last read
1081 | -O file # you own file
1082 | -G file # file's group ID matches yours (or one of yours, if you are in multiple groups)
1083 |
1084 | file1 -nt file2 # file1 is newer than file2
1085 | file1 -ot file2 # file1 is older than file2
1086 |
1087 | -lt # less than
1088 | -le # less than or equal
1089 | -eq # equal
1090 | -ge # greater than or equal
1091 | -gt # greater than
1092 | -ne # not equal
1093 | ```
1094 |
1095 | ## 2.6. Loops
1096 |
1097 | There are three types of loops in bash. `for`, `while` and `until`.
1098 |
1099 | Different `for` Syntax:
1100 | ```bash
1101 | for x := 1 to 10 do
1102 | begin
1103 | statements
1104 | end
1105 |
1106 | for name [in list]
1107 | do
1108 | statements that can use $name
1109 | done
1110 |
1111 | for (( initialisation ; ending condition ; update ))
1112 | do
1113 | statements...
1114 | done
1115 | ```
1116 |
1117 | `while` Syntax:
1118 | ```bash
1119 | while condition; do
1120 | statements
1121 | done
1122 | ```
1123 |
1124 | `until` Syntax:
1125 | ```bash
1126 | until condition; do
1127 | statements
1128 | done
1129 | ```
1130 |
1131 | # 3. Tricks
1132 |
1133 | ## Set an alias
1134 |
1135 | Run `nano ~/.bash_profile` and add the following line:
1136 |
1137 | ```bash
1138 | alias dockerlogin='ssh www-data@adnan.local -p2222' # add your alias in .bash_profile
1139 | ```
1140 |
1141 | ## To quickly go to a specific directory
1142 |
1143 | Run `nano ~/.bashrc` and add the following line:
1144 |
1145 | ```bash
1146 | export hotellogs="/workspace/hotel-api/storage/logs"
1147 | ```
1148 |
1149 | Now you can use the saved path:
1150 |
1151 | ```bash
1152 | source ~/.bashrc
1153 | cd $hotellogs
1154 | ```
1155 |
1156 | ## Re-execute the previous command
1157 |
1158 | This goes back to the days before you could rely on keyboards to have an "up" arrow key, but can still be useful.
1159 | To run the last command in your history
1160 | ```bash
1161 | !!
1162 | ```
1163 | A common error is to forget to use `sudo` to prefix a command requiring privileged execution. Instead of typing the whole command again, you can:
1164 | ```bash
1165 | sudo !!
1166 | ```
1167 | This would change a `mkdir somedir` into `sudo mkdir somedir`.
1168 |
1169 | ## Exit traps
1170 |
1171 | Make your bash scripts more robust by reliably performing cleanup.
1172 |
1173 | ```bash
1174 | function finish {
1175 | # your cleanup here. e.g. kill any forked processes
1176 | jobs -p | xargs kill
1177 | }
1178 | trap finish EXIT
1179 | ```
1180 |
1181 | ## Saving your environment variables
1182 |
1183 | When you do `export FOO = BAR`, your variable is only exported in this current shell and all its children, to persist in the future you can simply append in your `~/.bash_profile` file the command to export your variable
1184 | ```bash
1185 | echo export FOO=BAR >> ~/.bash_profile
1186 | ```
1187 |
1188 | ## Accessing your scripts
1189 |
1190 | You can easily access your scripts by creating a bin folder in your home with `mkdir ~/bin`, now all the scripts you put in this folder you can access in any directory.
1191 |
1192 | If you can not access, try append the code below in your `~/.bash_profile` file and after do `source ~/.bash_profile`.
1193 | ```bash
1194 | # set PATH so it includes user's private bin if it exists
1195 | if [ -d "$HOME/bin" ] ; then
1196 | PATH="$HOME/bin:$PATH"
1197 | fi
1198 | ```
1199 |
1200 | # 4. Debugging
1201 | You can easily debug the bash script by passing different options to `bash` command. For example `-n` will not run commands and check for syntax errors only. `-v` echo commands before running them. `-x` echo commands after command-line processing.
1202 |
1203 | ```bash
1204 | bash -n scriptname
1205 | bash -v scriptname
1206 | bash -x scriptname
1207 | ```
1208 |
1209 | ## Contribution
1210 |
1211 | - Report issues [How to](https://help.github.com/articles/creating-an-issue/)
1212 | - Open pull request with improvements [How to](https://help.github.com/articles/about-pull-requests/)
1213 | - Spread the word
1214 |
1215 | ## Translation
1216 | - [Chinese | 简体中文](https://github.com/vuuihc/bash-guide)
1217 | - [Turkish | Türkçe](https://github.com/omergulen/bash-guide)
1218 | - [Japanese | 日本語](https://github.com/itooww/bash-guide)
1219 |
1220 | ## License
1221 |
1222 | [](https://creativecommons.org/licenses/by/4.0/)
1223 |
--------------------------------------------------------------------------------