{"id":22369266,"url":"https://github.com/tushcmd/bash-tush","last_synced_at":"2025-03-26T16:20:38.950Z","repository":{"id":247804415,"uuid":"821871227","full_name":"tushcmd/bash-tush","owner":"tushcmd","description":null,"archived":false,"fork":false,"pushed_at":"2024-07-10T15:44:23.000Z","size":6,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-31T19:14:10.298Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tushcmd.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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}},"created_at":"2024-06-29T17:19:26.000Z","updated_at":"2024-07-10T15:44:27.000Z","dependencies_parsed_at":"2024-07-10T19:13:26.718Z","dependency_job_id":null,"html_url":"https://github.com/tushcmd/bash-tush","commit_stats":null,"previous_names":["tushcmd/bash-tush"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tushcmd%2Fbash-tush","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tushcmd%2Fbash-tush/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tushcmd%2Fbash-tush/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tushcmd%2Fbash-tush/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tushcmd","download_url":"https://codeload.github.com/tushcmd/bash-tush/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245689474,"owners_count":20656418,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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-12-04T19:19:27.831Z","updated_at":"2025-03-26T16:20:38.925Z","avatar_url":"https://github.com/tushcmd.png","language":"Shell","funding_links":[],"categories":[],"sub_categories":[],"readme":"# BASH Notes\n\n## Introduction\n\u003cbr\u003e\n\n### What is BASH?\n\n+ A shell language\n+ Short for **Bourne Again Shell**\n+ Easy Commands.\n\n### Why learn BASH?\n+ Most used and popular shell language.\n+ Used since early days of linux\n+ Comes with Linux and other OS(MAC, windows using WSL)\n\n### Why not BASH?\n+ Lacks features needed for Advance scripts\n+ No OOP\n+ Difficult syntax compared to Python\n+ Newer tools available like Ansible\n+ Advanced script python is preferred.\n\n### Still useful\n+ Lightweight and always available.\n+ Basic knowledge makes big difference.\n\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n## Understanding BASH script file\n\u003cbr\u003e\n\n```bash\n#!/bin/bash\n\n#Prompt the user for their name\necho \"Please enter your name: \"\n\n#Read the user's input into the name variable\nread name\n\n#Print a greeting message\necho \" Hello , $name!\"\n```\n\nConsider the above example\n1. **Shebang(#! line)**:  A bash script usually starts with a shebang line at the beginning, which tells the system which interpreter to use to execute the script.\n\n2. **Comment** : Use '#'\n\n3. **Variable**: Variable names are case sensitive and can contain letters, numbers and underscore in the name.\n4. **Command Execution**: Commands are typically written one per line and they are executed sequentially from top to bottom.\n5. **Control Structure**: Conditional(if-else-then), loops(for,while,until) and case.\n\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n## Positional Arguments\n\n1. $0: Represents the name of the script or command shell\n2. $1: first positional argument\n3. $2: second positional argument\n    .\n    .\n    .\n    $n: nth positional argument\n\nExample the script below: \n```bash\n#!/bin/bash\n\n# Check if at least two positional arguments are provided\nif [ $# -ge 2 ]; then\n    echo \"The first argument is: $1\"\n    echo \"The second argument is: $2\"\nelse\n    echo \"Usage: $0 \u003carg1\u003e \u003carg2\u003e\"\nfi\n```\n\nThe script is called in below format\n```cmd\n./test.sh arg1 arg2\n```\n\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n## Output/Input redirection in shell\n\u003cbr\u003e\nOutput redirection in shell scripting allows you to change the destination of the output generated by a command or script. By default, the output of a command is usually displayed in the terminal (standard output, often denoted as `stdout`). However, you can use redirection operators to send the output to a file or to another command's input. Here are some common output redirection operators in shell scripting:\n\n1. `\u003e` (Greater Than Symbol): This operator redirects standard output to a file. If the file does not exist, it is created; if it exists, it is overwritten. For example:\n   \n   ```bash\n   command \u003e output.txt\n   ```\n\n2. `\u003e\u003e` (Double Greater Than Symbol): This operator appends standard output to a file. If the file does not exist, it is created; if it exists, the output is added to the end of the file. For example:\n   \n   ```bash\n   command \u003e\u003e output.txt\n   ```\n\n3. `2\u003e` (Greater Than Symbol Followed by 2): This operator redirects standard error (stderr) to a file. For example:\n   \n   ```bash\n   command 2\u003e error.txt\n   ```\n\n4. `2\u003e\u003e` (Double Greater Than Symbol Followed by 2): This operator appends standard error (stderr) to a file. For example:\n   \n   ```bash\n   command 2\u003e\u003e error.txt\n   ```\n\n5. `\u0026\u003e` or `\u0026\u003e\u003e`: These operators redirect both standard output and standard error to a file. For example:\n   \n   ```bash\n   command \u0026\u003e output_and_error.txt\n   ```\n\n6. `\u003c` (Less Than Symbol): This operator is used for input redirection, allowing you to read data from a file as input for a command. For example:\n   \n   ```bash\n   command \u003c input.txt\n   ```\n7. `\u003c\u003c` (Double Less than symbol): Allows you to create a here document, which is a way to provide input to a command within your script. The content between \u003c\u003c EOF and EOF is treated as input to the command. This is particularly useful when you want to provide multiple lines of input or specify configuration settings.\nFor example:\n    ```bash\n    # Use a here document to provide input to 'cat'\n    cat \u003c\u003c EOF\n    This is line 1\n    This is line 2\n    EOF\n    ```\n7. `|` (Pipe Symbol): This operator is used for piping the output of one command as input to another command. It doesn't create files but is a way to pass data between commands. For example:\n   \n   ```bash\n   command1 | command2\n   ```\n\nHere are some examples of how to use output redirection:\n\n- Redirect standard output to a file:\n  ```bash\n  echo \"Hello, World!\" \u003e output.txt\n  ```\n\n- Redirect standard error to a file:\n  ```bash\n  command_that_generates_error 2\u003e error.txt\n  ```\n\n- Redirect both standard output and standard error to a file:\n  ```bash\n  command \u0026\u003e output_and_error.txt\n  ```\n\n- Append standard output to an existing file:\n  ```bash\n  echo \"This is additional text.\" \u003e\u003e existing_file.txt\n  ```\n\n- Pipe the output of one command as input to another:\n  ```bash\n  cat input.txt | grep \"pattern\"\n  ```\n\nOutput redirection is a powerful feature in shell scripting that allows you to control where the output of commands goes, making it useful for logging, capturing results, and processing data.\n\nInput redirection allows you to automate tasks by providing data to commands or scripts without manual user input. It's a valuable feature for processing files, configuration, and other data sources within shell scripts.\n\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n## Test Operators in shell\n\u003cbr\u003e\nIn shell scripting, test operators are used to evaluate conditions and return a Boolean result (true or false) based on the outcome of the test. The `test` command, often used with square brackets `[ ]`, is commonly used for conditional checks within shell scripts. Alternatively, you can use the `[[ ]]` construct in Bash for more advanced and flexible tests. Here are some commonly used test operators:\n\n1. **Numeric Comparisons**:\n   - `-eq`: Equal to (e.g., `[ \"$a\" -eq \"$b\" ]` checks if `$a` is equal to `$b`).\n   - `-ne`: Not equal to (e.g., `[ \"$a\" -ne \"$b\" ]` checks if `$a` is not equal to `$b`).\n   - `-lt`: Less than (e.g., `[ \"$a\" -lt \"$b\" ]` checks if `$a` is less than `$b`).\n   - `-le`: Less than or equal to (e.g., `[ \"$a\" -le \"$b\" ]` checks if `$a` is less than or equal to `$b`).\n   - `-gt`: Greater than (e.g., `[ \"$a\" -gt \"$b\" ]` checks if `$a` is greater than `$b`).\n   - `-ge`: Greater than or equal to (e.g., `[ \"$a\" -ge \"$b\" ]` checks if `$a` is greater than or equal to `$b`).\n\n2. **String Comparisons**:\n   - `=`: Equal to (e.g., `[ \"$str1\" = \"$str2\" ]` checks if `$str1` is equal to `$str2`).\n   - `!=`: Not equal to (e.g., `[ \"$str1\" != \"$str2\" ]` checks if `$str1` is not equal to `$str2`).\n\n3. **File Tests**:\n   - `-e`: Checks if a file exists (e.g., `[ -e \"$filename\" ]`).\n   - `-f`: Checks if a file exists and is a regular file (not a directory or a special file).\n   - `-d`: Checks if a directory exists.\n   - `-s`: Checks if a file is not empty (size greater than zero).\n   - `-r`, `-w`, `-x`: Checks if a file is readable, writable, or executable, respectively.\n\n4. **Logical Operators**:\n   - `!`: Negation (e.g., `[ ! -e \"$filename\" ]` checks if the file does not exist).\n   - `-a`: Logical AND (e.g., `[ \"$a\" -eq 1 -a \"$b\" -eq 2 ]` checks if both conditions are true).\n   - `-o`: Logical OR (e.g., `[ \"$a\" -eq 1 -o \"$b\" -eq 2 ]` checks if at least one condition is true).\n\n5. **String Tests**:\n   - `-z`: Checks if a string is empty (e.g., `[ -z \"$str\" ]`).\n   - `-n`: Checks if a string is not empty (e.g., `[ -n \"$str\" ]`).\n\n6. **File Comparisons**:\n   - `file1 -nt file2`: Checks if `file1` is newer than `file2`.\n   - `file1 -ot file2`: Checks if `file1` is older than `file2`.\n\nThese operators can be used in conditional statements such as `if`, `elif`, and `while` to perform tests and make decisions within shell scripts. For example:\n\n```bash\nif [ \"$a\" -eq 10 ]; then\n    echo \"The value of 'a' is 10.\"\nfi\n\nif [ -e \"$filename\" ]; then\n    echo \"The file exists.\"\nelse\n    echo \"The file does not exist.\"\nfi\n```\n\nKeep in mind that you can also use the `[[ ]]` construct in Bash for more advanced and flexible conditional tests, which provide additional capabilities, such as pattern matching and logical operators.\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n## If/Elif/Else\n\u003cbr\u003e\nThe `if`, `elif` (short for \"else if\"), and `else` statements are used in shell scripting and various programming languages to control the flow of a program based on conditional tests. They allow you to execute different blocks of code depending on whether certain conditions are true or false. Here's the basic syntax for using `if`, `elif`, and `else` statements in shell scripts:\n\u003cbr\u003e\n\u003cbr\u003e\n\n```bash\nif condition1; then\n    # Code to execute if condition1 is true\nelif condition2; then\n    # Code to execute if condition1 is false and condition2 is true\nelse\n    # Code to execute if neither condition1 nor condition2 is true\nfi\n```\n\n- `if`: The `if` statement is used to test a condition. If the condition is true, the code block following `then` is executed.\n\n- `elif`: The `elif` statement is used to test an alternative condition if the previous `if` condition is false. You can have multiple `elif` statements to test different conditions sequentially.\n\n- `else`: The `else` statement is optional and is executed if none of the previous conditions (including the `if` and any `elif` statements) are true.\n\nHere's an example of how `if`, `elif`, and `else` statements can be used in a shell script:\n\n```bash\n#!/bin/bash\n\nscore=85\n\nif [ \"$score\" -ge 90 ]; then\n    echo \"Grade: A\"\nelif [ \"$score\" -ge 80 ]; then\n    echo \"Grade: B\"\nelif [ \"$score\" -ge 70 ]; then\n    echo \"Grade: C\"\nelif [ \"$score\" -ge 60 ]; then\n    echo \"Grade: D\"\nelse\n    echo \"Grade: F\"\nfi\n```\n\nIn the above script, based on the value of the `score` variable, it determines the corresponding grade using `if`, `elif`, and `else` statements.\n\n- If `score` is greater than or equal to 90, it prints \"Grade: A\".\n- If `score` is between 80 and 89, it prints \"Grade: B\".\n- If `score` is between 70 and 79, it prints \"Grade: C\".\n- If `score` is between 60 and 69, it prints \"Grade: D\".\n- If `score` is below 60, it prints \"Grade: F\".\n\nYou can use `if`, `elif`, and `else` statements to handle more complex conditional logic and make decisions within your shell scripts based on various conditions.\n\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n## Case statements\n\u003cbr\u003e\n\n\u003e They are better than if/elif/else when\n\u003e\n\u003e- Checking for multiple values\n\u003e- is easier to read\n\nIn shell scripting, a case statement is used for conditional branching, allowing you to execute different blocks of code based on the value of a variable or an expression. A case statement is particularly useful when you have multiple conditions to check and want a more structured and readable way to handle them.\n\nThe basic syntax of a case statement in Bash looks like this:\n\n```bash\ncase expression in\n    pattern1)\n        # Code to execute if expression matches pattern1\n        ;;\n    pattern2)\n        # Code to execute if expression matches pattern2\n        ;;\n    ...\n    patternN)\n        # Code to execute if expression matches patternN\n        ;;\n    *)\n        # Default code to execute if none of the patterns match\n        ;;\nesac\n```\n\nHere's a breakdown of how a case statement works:\n\n- `case`: Begins the case statement.\n- `expression`: The value or variable you want to evaluate.\n- `in`: Separates the expression from the patterns.\n- `pattern1`, `pattern2`, ..., `patternN`: Patterns to match against the expression.\n- `)` (right parenthesis): Marks the end of each pattern.\n- `;;` (double semicolon): Separates each code block associated with a pattern.\n- `*)`: A wildcard pattern that matches anything. It is used as a default case if none of the patterns match.\n- `esac`: Marks the end of the case statement.\n\nHere's an example of a case statement in a shell script:\n\n```bash\n#!/bin/bash\n\nfruit=\"apple\"\n\ncase \"$fruit\" in\n    \"apple\")\n        echo \"It's an apple.\"\n        ;;\n    \"banana\")\n        echo \"It's a banana.\"\n        ;;\n    \"orange\")\n        echo \"It's an orange.\"\n        ;;\n    *)\n        echo \"It's something else.\"\n        ;;\nesac\n```\n\nIn this script, the value of the `fruit` variable is checked against different patterns, and the corresponding block of code is executed based on the match. In this case, it will print \"It's an apple.\"\n\nYou can have as many patterns as needed, and each pattern can contain multiple conditions. Case statements are particularly useful when you have a finite number of options to check, making your code more structured and easier to read than a series of `if`/`elif`/`else` statements for each condition.\n\n\u003cbr\u003e\n\u003cbr\u003e\n\n## Arrays\nYou can assign multiple values to one variable collected in a list which we call them `arrays`.\n\u003cbr\u003e\n\u003cbr\u003e\nYou can create them like this:\n```bash\nVariableName=(value1 value2 value3 value3)\n```\n- `VariableName`: Name of the array you want.\n- `()` (brackets): You can use which of `()`, `[]`, `{}` but you should remember to use the same opening and closing brackets.\n- ` ` (space): Each index of values separated by space.\n\u003cbr\u003e\n\nTo call them you should do\n\n```bash\n${VariableName[index]}\n```\n- `VariableName`: Name of the array you Initialized.\n- `index`: The index number you want. Indexes start from `0`. To use all of the indexes in your array you can use `@` as your index.\n\u003cbr\u003e\n\nYou can declare an empty array too. Here's how to do it:\n\n```bash\ndeclare -a \u003carray_name\u003e\n```\n\n- `declare`: Bash command used to explicitly set the array variable attribute.\n- `-a`: Option indicating the declaration of an indexed array.\n-  `\u003carray_name\u003e`: The name you want to assign to the array.\n\n```bash\ndeclare -a MyArray\n```\n\n\u003cbr\u003e\n\nFor adding new values after declaration you can do either of these:\n\n```bash\narray_name[position]=value\n```\n- `array_name`: The name of the array you assign.\n- `position`: The index at which you want to assign value.\n- `value`: The item you insert to the specified index.\n\n```bash\nMyArray[1]=one\n```\n\nor\n\n```bash\narray_name+=(item item item)\n```\n\n- `array_name`: The name of the array you assign.\n- `+=`: Compound operator to add array elements.\n- `item`: Value you want to put in your array.\n\n```bash\nMyArray+=(one two three)\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftushcmd%2Fbash-tush","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftushcmd%2Fbash-tush","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftushcmd%2Fbash-tush/lists"}