{"id":13641887,"url":"https://github.com/cheatsnake/bash-scripts-by-example","last_synced_at":"2026-01-21T21:46:56.010Z","repository":{"id":171071331,"uuid":"591891505","full_name":"cheatsnake/bash-scripts-by-example","owner":"cheatsnake","description":"Learn main features of Bash scripts by examples","archived":false,"fork":false,"pushed_at":"2025-04-07T17:46:04.000Z","size":68,"stargazers_count":50,"open_issues_count":0,"forks_count":16,"subscribers_count":2,"default_branch":"master","last_synced_at":"2026-01-15T20:23:54.523Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cheatsnake.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-01-22T08:36:55.000Z","updated_at":"2026-01-02T16:43:55.000Z","dependencies_parsed_at":"2024-01-14T12:17:19.431Z","dependency_job_id":"86b29803-42d3-4867-8878-0b34aec2133e","html_url":"https://github.com/cheatsnake/bash-scripts-by-example","commit_stats":null,"previous_names":["cheatsnake/bash-scripts-by-example"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/cheatsnake/bash-scripts-by-example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheatsnake%2Fbash-scripts-by-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheatsnake%2Fbash-scripts-by-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheatsnake%2Fbash-scripts-by-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheatsnake%2Fbash-scripts-by-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cheatsnake","download_url":"https://codeload.github.com/cheatsnake/bash-scripts-by-example/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheatsnake%2Fbash-scripts-by-example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28644149,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-21T21:29:11.980Z","status":"ssl_error","status_checked_at":"2026-01-21T21:24:31.872Z","response_time":86,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T01:01:25.407Z","updated_at":"2026-01-21T21:46:55.988Z","avatar_url":"https://github.com/cheatsnake.png","language":null,"funding_links":[],"categories":["Linux Basics","Tools"],"sub_categories":["Bash"],"readme":"# Bash scripts by example\n\n[`English`](https://github.com/cheatsnake/bash-scripts-by-example/blob/master/README.md) [`Russian`](https://github.com/cheatsnake/bash-scripts-by-example/blob/master/README_RUS.md)\n\n**Bash scripts** are sets of the same commands that can be entered from the keyboard, but compiled into a single file and united by some common purpose. This approach allows you to automate a lot of routine tasks such as building projects or installing new programs. Bash is easy to learn and use, flexible and somehow present in the vast majority of Linux distributions.\n\nBash scripts have an extension `.sh`:\n\n```\n$ touch script.sh\n```\n\nIt is good practice to specify the path to your terminal at the beginning of each script:\n\n```sh\n#!/bin/bash\n```\n\n\u003e This technique is called **shebang**, you can read more about it [here](\u003chttps://en.wikipedia.org/wiki/Shebang_(Unix)\u003e).\n\nA list of available terminals on your system can be viewed with this command:\n\n```\n$ cat /etc/shells\n```\n\n## Content\n\n- [Bash scripts by example](#bash-scripts-by-example)\n  - [Content](#content)\n  - [Hello world](#hello-world)\n  - [Comments](#comments)\n  - [Variables](#variables)\n  - [User input](#user-input)\n  - [Passing arguments](#passing-arguments)\n  - [Conditions if else](#conditions-if-else)\n  - [Comparison operators](#comparison-operators)\n    - [Comparison operators for numbers](#comparison-operators-for-numbers)\n    - [Comparison operators for strings](#comparison-operators-for-strings)\n    - [Comparison operators for files](#comparison-operators-for-files)\n  - [Logical operators](#logical-operators)\n  - [Arithmetic operators](#arithmetic-operators)\n  - [Switch case](#switch-case)\n  - [Arrays](#arrays)\n  - [While loop](#while-loop)\n  - [Until loop](#until-loop)\n  - [For loop](#for-loop)\n  - [Select loop](#select-loop)\n  - [Break and continue keywords](#break-and-continue-keywords)\n  - [Functions](#functions)\n  - [Local variables](#local-variables)\n  - [Keyword readonly](#keyword-readonly)\n  - [Signal processing](#signal-processing)\n  - [Debugging scripts](#debugging-scripts)\n  - [Additional materials](#additional-materials)\n\n## Hello world\n\n```sh\n#!/bin/bash\necho \"Hello world\"\n```\n\nRunning a script:\n\n```\n$ bash script.sh\n```\n\nThe script can be made into an executable file and run without the `bash` command:\n\n```\n$ chmod +x script.sh\n```\n\n```\n$ ./script.sh\n```\n\n## Comments\n\nOne line comments:\n\n```sh\n# This is comment\n# And that too\necho \"Hello from bash\" # this command outputs a line into the console\n```\n\nMultiline comments:\n\n```sh\n: 'Multi-line comments are very handy\nto describe your scripts in detail.\nUse them wisely!'\n```\n\n## Variables\n\n```sh\nMY_STRING=\"bash is cool\"\necho $MY_STRING # Output the value of a variable\n```\n\n\u003e The variable name must not begin with a number\n\n## User input\n\nThe `read` command reads user input and writes it to the specified variable:\n\n```sh\necho \"Input your name:\"\nread NAME\necho \"Hello, $NAME!\"\n```\n\n\u003e If no variable is specified, the `read` command will by default save all data to the `REPLY` variable\n\nYou can write multiple variables. To do this, when entering from the terminal, the values must be separated by a space:\n\n```sh\nread V1 V2 V3\necho \"1st var: $V1\"\necho \"2nd var: $V2\"\necho \"3rd var: $V3\"\n```\n\n```\n$ bash script.sh\n$ hello world some other text\n1st var: hello\n2nd var: world\n3rd var: some other text\n```\n\nThe `-a` flag allows you to create an array in which user input lines separated by spaces will be written:\n\n```sh\nread -a NAMES\necho \"Array of names: ${NAMES[0]}, ${NAMES[1]}, ${NAMES[2]}\"\n```\n\n```\n$ bash script.sh\nAlex Mike John\nArray of names: Alex, Mike, John\n```\n\nThe `-p` flag allows you not to carry user input to the next line.\n\nThe `-s` flag allows you to hide the characters you enter (as you do when entering a password).\n\n```sh\nread -p \"Enter your login: \" LOGIN\nread -sp \"Enter your password: \" PASSWD\n```\n\n```\n$ bash script.sh\nEnter your login: bash_hacker\nEnter your password: ******\n```\n\n## Passing arguments\n\nArguments are simply values that can be specified when running the script.\n\nAll passed arguments are assigned a unique name equal to their ordinal number:\n\n```sh\necho \"Argument 1 - $1; argument 1 - $2; argument 1 - $3.\"\n```\n\n```\n$ bash script.sh hello test 1337\nArgument 1 - hello; argument 1 - test; argument 1 - 1337.\n```\n\nThe null argument is always the name of the script file:\n\n```sh\necho \"You have run the file $0\"\n```\n\n```\n$ bash script.sh\nYou have run the file script.sh\n```\n\nAll arguments can be put into a named array:\n\n```sh\nargs=(\"$@\")\necho \"Arguments received: ${args[0]}, ${args[1]}, ${args[2]}.\"\n```\n\n```\n$ bash script.sh some values 123\nArguments received: some, values, 123\n```\n\n\u003e `@` - is the name of the default array that stores all the arguments (except for the null one)\n\nThe number of arguments passed (with the exception of zero) is stored in the `#` variable:\n\n```sh\necho \"Total arguments received: $#\"\n```\n\n## Conditions if else\n\nConditions always start with the keyword `if` and end with `fi`:\n\n```sh\necho \"Enter your age:\"\nread AGE\n\nif (($AGE \u003e= 18))\nthen\n\techo \"Access allowed\"\nelse\n\techo \"Access denied\"\nfi\n```\n\n```\n$ bash script.sh\nEnter your age:\n19\nAccess allowed\n\n$ bash script.sh\nEnter your age:\n16\nAccess denied\n```\n\nThere can be as many conditions as you want, for this purpose the construct `elif` is used, which also as `if` can check conditions:\n\n```sh\nread COMMAND\n\nif [ $COMMAND = \"help\" ]\nthen\n\techo \"Available commands:\"\n\techo \"ping - will return the PONG string\"\n\techo \"version - returns the version of the program\"\nelif [ $COMMAND = \"ping\" ]\nthen\n\techo \"PONG\"\nelif [ $COMMAND = \"version\" ]\nthen\n\techo \"v1.0.0\"\nelse\n\techo \"The command is not defined. Use the 'help' command for help.\"\nfi\n```\n\n\u003e Note that the `if` and `elif` constructions are always followed by a line with the keyword `then`. \u003cbr\u003e\n\u003e Also remember to separate conditions with spaces inside the curly braces -\u003e `[ condition ]`.\n\n## Comparison operators\n\nDifferent comparison operators can be used for numbers and strings. Their complete lists with examples are given in the tables below.\n\n\u003e Note that different operators are used with certain brackets\n\n### Comparison operators for numbers\n\n| Operator | Description              | Example            |\n| -------- | ------------------------ | ------------------ |\n| -eq      | is equal to              | if [ $age -eq 18 ] |\n| -ne      | does not equal           | if [ $age -ne 18 ] |\n| -gt      | more than                | if [ $age -gt 18 ] |\n| -ge      | greater than or equal to | if [ $age -ge 18 ] |\n| -lt      | less than                | if [ $age -lt 18 ] |\n| -le      | less than or equal to    | if [ $age -le 18 ] |\n| \u003e        | more than                | if (($age \u003e 18))   |\n| \u003c        | less than                | if (($age \u003c 18))   |\n| =\u003e       | greater than or equal to | if (($age =\u003e 18))  |\n| \u003c=       | less than or equal to    | if (($age \u003c= 18))  |\n\n### Comparison operators for strings\n\n| Operator | Description                                            | Example                |\n| -------- | ------------------------------------------------------ | ---------------------- |\n| =        | equality check                                         | if [ $str = \"hello\" ]  |\n| ==       | equality check                                         | if [ $str == \"hello\" ] |\n| !=       | check for NOT equality                                 | if [ $str != \"hello\" ] |\n| \u003c        | comparison less than ASCII character code              | if [[$str \u003c \"hello\"]]  |\n| \u003e        | comparison of more than the ASCII character code       | if [[$str \u003e \"hello\"]]  |\n| -z       | check if the string is empty                           | if [ -z $str ]         |\n| -n       | check if there is at least one character in the string | if [ -n $str ]         |\n\nThere are also operators for checking various conditions on files:\n\n### Comparison operators for files\n\n| Operator | Description                                                               | Example         |\n| -------- | ------------------------------------------------------------------------- | --------------- |\n| -e       | checks if a file exists                                                   | if [ -e $file ] |\n| -s       | checks if a file is empty                                                 | if [ -s $file ] |\n| -f       | checks if the file is a normal file and not a directory or a special file | if [ -f $file ] |\n| -d       | checks if the file is a directory                                         | if [ -d $file ] |\n| -r       | checks if the file is readable                                            | if [ -r $file ] |\n| -w       | checks if the file is writable                                            | if [ -w $file ] |\n| -x       | checks if the file is executable                                          | if [ -x $file ] |\n\n## Logical operators\n\nConditions with the \"AND\" operator return true only when all conditions are true.\n\n\u003e There are several options for writing conditions with logical operators\n\n```sh\nif [ $age -ge 18 ] \u0026\u0026 [ $age -le ]\n```\n\n```sh\nif [ $age -ge 18 -a $age -le ]\n```\n\n```sh\nif [[ $age -ge 18 \u0026\u0026 $age -le ]]\n```\n\nConditions with an OR operator return true when at least one condition is true.\n\n```sh\nif [ -r $file ] || [ -w $file ]\n```\n\n```sh\nif [ -r $file -o -w $file ]\n```\n\n```sh\nif [[ -r $file || -w $file ]]\n```\n\n## Arithmetic operators\n\n```bash\nnum1=10\nnum2=5\n\n# Addition\necho $((num1 + num2))      # 15\necho $(expr $num1 + $num2) # 15\n\n# Subtraction\necho $((num1 - num2))      # 5\necho $(expr $num1 - $num2) # 5\n\n# Multiplication\necho $((num1 * num2))       # 50\necho $(expr $num1 \\* $num2) # 50\n\n# Division\necho $((num1 / num2))      # 2\necho $(expr $num1 / $num2) # 2\n\n# Residue from division\necho $((num1 % num2))      # 0\necho $(expr $num1 % $num2) # 0\n```\n\n\u003e Note that when using multiplication with the `expr` keyword you must use a slash.\n\n## Switch case\n\nIt is not always convenient to use if/elif constructions for a large number of conditions. The case construct is better suited for this purpose:\n\n```sh\nread COMMAND\n\ncase $COMMAND in\n\t\"/help\" )\n\t\techo \"You opened the help menu\" ;;\n\t\"/ping\" )\n\t\techo \"PONG\" ;;\n\t\"/version\" )\n\t\techo \"Version: 1.0.0\" ;;\n\t* )\n\t\techo \"There is no such command :(\" ;;\nesac\n```\n\n\u003e The case with the asterisk \\* will only work if none of the conditions above fit.\n\n## Arrays\n\nArrays allow you to store an entire collection of data in a single variable. This variable can be conveniently and easily interacted with.\n\n```sh\narray=('aaa' 'bbb' 'ccc' 'ddd')\n\necho \"Array elements: ${array[@]}\"\necho \"First element of the array: ${array[0]}\"\necho \"Array element indexes: ${!array[@]}\"\n\narray_length=${#array[@]}\necho \"Array length: ${array_length}\"\necho \"The last element of the array: ${array[$((array_length - 1))]}\"\n```\n\n```\n$ bash script.sh\nArray elements: aaa bbb ccc ddd\nFirst element of the array: aaa\nArray element indexes: 0 1 2 3\nArray length: 4\nThe last element of the array: ddd\n```\n\n\u003e Note that the array elements are separated by a space without a comma.\n\nArray elements can be added/rewritten/deleted as the script runs:\n\n```sh\narray=('a' 'b' 'c')\n\narray[3]='d'\necho ${array[@]} # a b c d\n\narray[0]='x'\necho ${array[@]} # x b c d\n\narray[0]='x'\necho ${array[@]} # x b c d\n\nunset array[2]\necho ${array[@]} # x b d\n```\n\n## While loop\n\nThe while loop repeats the execution of the block of code described between the `do` - `done` keywords until the given condition is true.\n\n```sh\ni=0\n\nwhile (( $i \u003c 5 ))\ndo\n\ti=$((i + 1))\n\techo \"Iteration number $i\"\ndone\n```\n\n```\n$ bash script.sh\nIteration number 1\nIteration number 2\nIteration number 3\nIteration number 4\nIteration number 5\n```\n\nThe operation of increasing a number by 1 unit is called an increment, and there is a special notation for it:\n\n```sh\n(( i++ )) # post increment\n```\n\n```sh\n(( ++i )) # pre increment\n```\n\nThe opposite operation is decrement:\n\n```sh\n(( i-- )) # post decrement\n```\n\n```sh\n(( --i )) # pre decrement\n```\n\nWith while cycles you can read different files line by line. There are several ways to do this:\n\n```sh\necho \"Reading a file line by line:\"\nwhile read line\ndo\n\techo $line\ndone \u003c text.txt\n```\n\n```sh\necho \"Reading a file line by line:\"\ncat text.txt | while read line\ndo\n\techo $line\ndone\n```\n\n```sh\necho \"Reading a file line by line:\"\nwhile IFS='' read -r line\ndo\n\techo $line\ndone \u003c text.txt\n```\n\n## Until loop\n\nThe until loop is opposite to the while loop in that it executes the block of code described between the `do` - `done` keywords when the given condition returns false:\n\n```sh\ni=5\nuntil (( $i == 0 )) # will be executed until i equals 0\ndo\n\techo \"Value of the variable i = $i\"\n\t(( i-- ))\ndone\n```\n\n```\n$ bash script.sh\nValue of the variable i = 5\nValue of the variable i = 4\nValue of the variable i = 3\nValue of the variable i = 2\nValue of the variable i = 1\n```\n\n## For loop\n\nThe most classic cycle.\n\n```sh\nfor (( i=1; i\u003c=10; i++ ))\ndo\n\techo $i\ndone\n```\n\nIn newer versions of Bash there is a more convenient way to write using the `in` operator:\n\n```sh\nfor i in {1..10}\ndo\n\techo $i\ndone\n```\n\nThe condition after the `in` keyword generally looks like this:\n\n```\n{START..END..INCREMENT}\n```\n\n\u003e _START_ - which number to start the cycle with; \u003cbr\u003e _END_ - up to which number to continue the cycle; \u003cbr\u003e _INCREMENT_ - by how much to increment the start number after each iteration (1 – by default).\n\nThe for loop can be used to run a set of commands sequentially:\n\n```sh\nfor command in ls pwd date # List of commands to run\ndo\n\techo \"---Running a command $command---\"\n\t$command\n\techo \"------------------------\"\ndone\n```\n\n```\n$ bash script.sh\n---Running a command ls---\nscript.sh  text.txt\n------------------------\n---Running a command pwd---\n/home/user/bash\n------------------------\n---Running a command date---\nSun Jan 22 10:35:51 AM +03 2023\n------------------------\n```\n\n## Select loop\n\nExtremely handy loop for creating a menu of option selections.\n\n```sh\nselect color in \"Red\" \"Green\" \"Blue\" \"White\"\ndo\n\techo \"You have selected $color color...\"\ndone\n```\n\n```\n$ bash script.sh\n1) Red\n2) Green\n3) Blue\n4) White\n#? 1\nYou have selected Red color...\n#? 2\nYou have selected Green color...\n#? 3\nYou have selected Blue color...\n#? 4\nYou have selected White color...\n```\n\nThe `select` loop combines very well with the `case` selection operator. This way you can very easily create interactive console applications with a lot of branching:\n\n```sh\necho \"---Welcome to the menu---\"\n\nselect cmd in \"Run\" \"Settings\" \"About\" \"Exit\"\ndo\n\tcase $cmd in\n\t\"Run\")\n\t\techo \"The program is running\"\n\t\techo \"Enter the number:\"\n\t\tread input\n\t\techo \"$input squared = $(( input * input ))\" ;;\n\t\"Settings\")\n\t\techo \"Program Settings\" ;;\n\t\"About\")\n\t\techo \"Version 1.0.0\" ;;\n\t\"Exit\")\n\t\techo \"Exiting the program...\"\n\t\tbreak ;;\n\tesac\ndone\n```\n\n## Break and continue keywords\n\nThe keyword `break` is used to force an exit from the loops:\n\n```sh\ncount=1\n\nwhile (($count)) # always returns the truth\ndo\n\tif (($count \u003e 10))\n\tthen\n\t\tbreak # forced exit in spite of the condition after while\n\telse\n\t\techo $count\n\t\t((count++))\n\tfi\ndone\n```\n\nThe `continue` keyword is used to skip the current iteration of the loop and go to the next one:\n\n```sh\nfor (( i=5; i\u003e0; i-- ))\ndo\n\tif ((i % 2 == 0))\n\tthen\n\t\tcontinue\n\tfi\n\n\techo $i\ndone\n```\n\n```\n$ bash script.sh\n5\n3\n1\n```\n\n## Functions\n\nFunctions are named code sections that can be reused an unlimited number of times.\n\n```sh\nhello() {\n\techo \"Hello World!\"\n}\n\n# Call the function 3 times:\nhello\nhello\nhello\n```\n\n```\n$ bash script.sh\nHello World!\nHello World!\nHello World!\n```\n\nFunctions, just like scripts themselves, can accept arguments. They have the same names, but function arguments are only visible inside the function to which they have been passed:\n\n```sh\necho \"$1\" # argument passed when running the script\n\ncalc () {\n\techo \"$1 + $2 = $(($1 + $2))\"\n}\n\n# passing two arguments to the calc function\ncalc 42 17\n```\n\n```\n$ bash script.sh hello\nhello\n42 + 17 = 59\n```\n\n## Local variables\n\nIf we declare a variable and then declare another one with the same name, but inside the function, we have an overwrite:\n\n```sh\nVALUE=\"hello\"\n\ntest() {\n\tVALUE=\"linux\"\n}\n\ntest\necho $VALUE\n```\n\n```\n$ bash script.sh\nlinux\n```\n\nTo prevent this behavior, the `local` keyword is used in front of the variable name that is declared inside a function:\n\n```sh\nVALUE=\"hello\"\n\ntest() {\n\tlocal VALUE=\"linux\"\n\techo \"Variable inside a function: $VALUE\"\n}\n\ntest\necho \"Global variable: $VALUE\"\n```\n\n```\n$ bash script.sh\nVariable inside a function: linux\nGlobal variable: hello\n```\n\n## Keyword readonly\n\nBy default, every variable created in Bash can subsequently be overwritten. To protect a variable from changes you can use the `readonly` keyword:\n\n```sh\nreadonly PI=3.14\nPI=100\n\necho \"PI = $PI\"\n```\n\n```\n$ bash script.sh\nscript.sh: line 2: PI: readonly variable\nPI = 3.14\n```\n\n`readonly` can be used not only at the time the variable is declared, but also afterwards:\n\n```sh\nVALUE=123\nVALUE=$(($VALUE * 1000))\nreadonly VALUE\nVALUE=555\n\necho $VALUE\n```\n\n```\n$ bash script.sh\nscript.sh: line 4: VALUE: readonly variable\n123000\n```\n\nThe same is true for functions. They can also be overridden, so you can protect them with `readonly` with the `-f` flag:\n\n```sh\ntest() {\n\techo \"This is test function\"\n}\n\nreadonly -f test\n\ntest() {\n\techo \"Hello World!\"\n}\n\ntest\n```\n\n```\n$ bash script.sh\nscript.sh: line 9: test: readonly function\nThis is test function\n```\n\n## Signal processing\n\nDuring the execution of scripts, unexpected actions may occur. For example, the user may interrupt the execution of the script with a combination of `Ctrl + C`, or may accidentally close the terminal or some error may occur in the script itself and so on...\n\nIn POSIX-systems, there are special signals - process notifications of some event. Their list is defined in the table below:\n\n| Signal  | Code     | Action                | Description                                                  |\n| ------- | -------- | --------------------- | ------------------------------------------------------------ |\n| SIGHUP  | 1        | Terminate             | Closing the terminal                                         |\n| SIGINT  | 2        | Terminate             | Interrupt signal (Ctrl-C) from the terminal                  |\n| SIGQUIT | 3        | Terminate (core dump) | The \"Quit\" signal from the terminal (Ctrl-)                  |\n| SIGILL  | 4        | Terminate (core dump) | Invalid CPU instruction                                      |\n| SIGABRT | 6        | Terminate (core dump) | Signal sent by abort()                                       |\n| SIGFPE  | 8        | Terminate (core dump) | Erroneous arithmetic operation                               |\n| SIGKILL | 9        | Terminate             | Process killed                                               |\n| SIGSEGV | 11       | Terminate (core dump) | Violation when accessing memory                              |\n| SIGPIPE | 13       | Terminate             | Writing to a broken connection (pipe, socket)                |\n| SIGALRM | 14       | Terminate             | Alarm expires when the time set by alarm() expires           |\n| SIGTERM | 15       | Terminate             | End signal (the default signal for the kill utility)         |\n| SIGUSR1 | 30/10/16 | Terminate             | User-defined signal № 1                                      |\n| SIGUSR2 | 31/12/17 | Terminate             | User-defined signal № 2                                      |\n| SIGCHLD | 20/17/18 | Ignore                | Subsidiary process completed or stopped                      |\n| SIGCONT | 19/18/25 | Continue              | Continue executing the previously stopped process            |\n| SIGSTOP | 17/19/23 | Stop                  | Stopping the process execution                               |\n| SIGTSTP | 18/20/24 | Stop                  | Stop signal from the terminal (Ctrl-Z)                       |\n| SIGTTIN | 21/21/26 | Stop                  | Attempting to read from the terminal by a background process |\n| SIGTTOU | 22/22/27 | Stop                  | Attempting to write to the terminal by a background process  |\n\nBash has a keyword `trap` which can be used to catch different signals and provide for certain commands:\n\n```\ntrap \u003cCOMMAND\u003e \u003cSIGNAL\u003e\n```\n\n\u003e Under the signal you can use its name (_Signal_ column in the table), or its code (_Code_ column in the table). You can specify several signals, separating their names or codes with a space. \u003cbr\u003e **Exceptions:** SIGKILL (9) and SIGSTOP (17/19/23) signals are impossible to catch, so there is no point in specifying them.\n\n```sh\ntrap \"echo Program execution interrupted...; exit\" SIGINT\n\nfor i in {1..10}\ndo\n\tsleep 1\n\techo $i\ndone\n```\n\n```\n$ bash script.sh\n1\n2\n3\n4\n^Program execution interrupted...\n```\n\n## Debugging scripts\n\nRunning the script with the `-x` parameter will show its step-by-step execution, which will be useful for debugging and searching for errors:\n\n```\n$ bash -x script.sh\n```\n\n## Additional materials\n\n1. 📄 [**Awesome Bash – curated list of delightful Bash scripts and resources** – GitHub](https://github.com/awesome-lists/awesome-bash)\n2. 📺 [**Write Your Own Bash Scripts for Automation** – YouTube](https://youtu.be/PPQ8m8xQAs8)\n3. 📘 [**Bash cookbook** – C. Albing, 2007](https://theswissbay.ch/pdf/Gentoomen%20Library/Programming/Bash/O%27Reilly%20bash%20CookBook.pdf)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcheatsnake%2Fbash-scripts-by-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcheatsnake%2Fbash-scripts-by-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcheatsnake%2Fbash-scripts-by-example/lists"}