{"id":19624352,"url":"https://github.com/sk-azraf-sami/basic-shell-programming","last_synced_at":"2026-05-17T14:32:46.836Z","repository":{"id":212771069,"uuid":"687801284","full_name":"Sk-Azraf-Sami/Basic-Shell-Programming","owner":"Sk-Azraf-Sami","description":"Basic of Bash Shell Script. Learn shell scripting basics: Bash commands, automation, and practice problems for efficient system management.","archived":false,"fork":false,"pushed_at":"2023-10-08T04:20:52.000Z","size":172,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-26T19:41:16.434Z","etag":null,"topics":["bash","bash-script","basic","linux","notes","operating-system","os"],"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/Sk-Azraf-Sami.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}},"created_at":"2023-09-06T03:13:36.000Z","updated_at":"2024-04-13T10:43:08.000Z","dependencies_parsed_at":"2023-12-16T07:36:31.229Z","dependency_job_id":"b909a465-7ab6-4353-9578-a58f84c2a525","html_url":"https://github.com/Sk-Azraf-Sami/Basic-Shell-Programming","commit_stats":null,"previous_names":["sk-azraf-sami/basic-shell-programming"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Sk-Azraf-Sami/Basic-Shell-Programming","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FBasic-Shell-Programming","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FBasic-Shell-Programming/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FBasic-Shell-Programming/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FBasic-Shell-Programming/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Sk-Azraf-Sami","download_url":"https://codeload.github.com/Sk-Azraf-Sami/Basic-Shell-Programming/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FBasic-Shell-Programming/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33142136,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-17T09:28:26.183Z","status":"ssl_error","status_checked_at":"2026-05-17T09:27:52.702Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6: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":["bash","bash-script","basic","linux","notes","operating-system","os"],"created_at":"2024-11-11T11:37:49.060Z","updated_at":"2026-05-17T14:32:42.305Z","avatar_url":"https://github.com/Sk-Azraf-Sami.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Basic-Shell-Programming\n\n## Table of Contents: \n- [Comments](#Comments)\n- [Shebang](#shebang)\n- [Data Types](#Data-Types)\n- [\\ is the bash escape character](#is-the-bash-escape-character)\n- [Single and Double Quote](#Single-and-Double-Quote)\n- [Read command](#Read-command)\n- [Command Substitution](#Command-Substitution)\n- [Arithmetic Evaluation](#Arithmetic-Evaluation)\n\n  \n## [Comments:](#Comments)\n\n**Single-Line Comments (Using `#`):**\n\n```bash\n#!/bin/bash\n\n# This is a single-line comment.\n# Single-line comments begin with the '#' symbol.\n# They are used to add explanatory notes or comments to your code.\n\necho \"Hello, world!\"  # This is another single-line comment.\n\n# You can have single-line comments anywhere in your script.\n# They can be on their own line or at the end of a line of code.\n```\n\nExplanation:\n- Single-line comments in shell scripting start with the `#` symbol.\n- They are used for adding comments or explanations to your code.\n- Anything following the `#` on a line is treated as a comment and is not executed by the shell.\n- Single-line comments can be placed on their own lines or at the end of lines with code.\n\n**Multi-Line Comments (Using Here Document):**\n\n```bash\n#!/bin/bash\n\n: '\nThis is a multi-line comment using a here document.\nMulti-line comments are not a standard feature of shell scripting,\nbut you can use a colon (:) followed by single quotes (') to create one.\nThe comment text goes between the single quotes.\nThis can span multiple lines.\n'\n\necho \"Hello, world!\"\n\n# The actual code starts here.\n```\n\nExplanation:\n- Multi-line comments are not a native feature of shell scripting, so this is a workaround using a colon and single quotes.\n- The colon (`:`) is a no-op (no operation) command that does nothing, and the single quotes (`'`) are used to create a block of text.\n- Anything between the single quotes is treated as a comment and is not executed.\n- This approach allows you to create multi-line comments, but it's not standard, and not all shells may support it.\n\nIn practice, single-line comments using `#` are the most commonly used form of comments in shell scripts because they are widely supported and straightforward. The multi-line comment using a here document is less common and less portable but can be useful when you need to comment out larger blocks of code or explanations.\n\n**In a shell script, you can use `\u003c\u003c`** (the here document syntax) to create multi-line comments instead of using `:` (the no-op command) followed by single quotes (`'`). Here's how you can use `\u003c\u003c` for multi-line comments:\n\n```bash\n#!/bin/bash\n\n\u003c\u003cCOMMENT\nThis is a multi-line comment using a here document.\nYou can include as many lines of comments as you need.\nThe comment text goes between the 'COMMENT' marker and the corresponding 'COMMENT' marker.\nThis block of text will not be executed.\nCOMMENT\n\necho \"Hello, world!\"\n\n# The actual code starts here.\n```\n\nExplanation:\n- In this example, the `\u003c\u003cCOMMENT` and `COMMENT` markers are used to delimit the multi-line comment block.\n- Anything between the `\u003c\u003cCOMMENT` and `COMMENT` markers is treated as a comment and is not executed.\n- The `COMMENT` marker can be replaced with any unique identifier you choose; it doesn't have to be uppercase or in all caps, but it should match consistently.\n\nUsing `\u003c\u003c` for multi-line comments can be a more readable and structured way to add comments to your code when compared to the `:` and single quotes approach. However, it's important to note that this is still not a standard feature of shell scripting, but it's a widely used convention for creating multi-line comments.\n\n## [Shebang](#shebang)\nThe line `#!/bin/bash` is called a shebang, also known as a hashbang or pound-bang. It is not required for a shell script to run, but it serves an important purpose.\n\nThe shebang is used to specify the interpreter that should be used to execute the script. In this case, `#!/bin/bash` indicates that the script should be interpreted and executed using the Bash shell.\n\nIf you don't include a shebang line at the beginning of your script, the script will still run, but it will be executed by the default shell of your system. This behavior may vary depending on the operating system and shell environment.\n\nHere are a few key points about the shebang line:\n\n1. **Interpreter Specification**: The shebang line tells the operating system which interpreter should be used to execute the script. Different scripts may use different interpreters, such as `/bin/bash` for Bash scripts, `/bin/python3` for Python scripts, or `/bin/perl` for Perl scripts.\n\n2. **Compatibility**: Including a shebang line is a good practice because it ensures that your script runs with the desired interpreter, making it more portable and avoiding potential compatibility issues.\n\n3. **Executable Permission**: To run a script as an executable (e.g., `./myscript.sh`), you need to give the script file execute permission (`chmod +x myscript.sh`). The shebang line is essential for the system to understand how to execute the script as an independent program.\n\n4. **Cross-Platform**: The shebang line makes it easier to share and distribute scripts because it explicitly specifies the interpreter, making the script self-contained.\n\nIn summary, while a shebang line is not strictly required, it is strongly recommended to include one at the beginning of your shell script to ensure proper interpretation and execution, enhance portability, and make it clear which interpreter the script should use.\n\n## [Data Types](#Data-Types)\nShell programming typically deals with a limited set of data types, primarily because the shell itself is designed for managing and manipulating text and running system commands. Here are some of the common data types used in shell programming with examples:\n\n1. **String**: Shell scripts frequently work with strings, which are sequences of characters.\n\n   ```bash\n   name=\"John\"\n   echo \"Hello, $name\"\n   ```\n\n2. **Integer**: Although shell scripting primarily handles strings, you can perform arithmetic operations on integers.\n\n   ```bash\n   x=5\n   y=3\n   result=$((x + y))\n   echo \"Result: $result\"\n   ```\n\n3. **Array**: Shell supports indexed arrays, allowing you to store multiple values in a single variable.\n\n   ```bash\n   fruits=(\"apple\" \"banana\" \"cherry\")\n   echo \"First fruit: ${fruits[0]}\"\n   ```\n\n4. **Associative Array (Bash)**: Bash supports associative arrays, allowing you to create key-value pairs.\n\n   ```bash\n   declare -A person\n   person[\"name\"]=\"John\"\n   person[\"age\"]=30\n   echo \"Name: ${person[\"name\"]}, Age: ${person[\"age\"]}\"\n   ```\n\n5. **Boolean**: While shell scripting doesn't have a native boolean data type, you can use numeric values (0 for false, 1 for true) to represent boolean conditions.\n\n   ```bash\n   is_true=1\n   is_false=0\n   ```\n\n6. **File Descriptor**: In addition to standard variables, shell scripting can work with file descriptors for input, output, and error handling.\n\n   ```bash\n   # Redirecting output to a file\n   echo \"Hello, world!\" \u003e output.txt\n   ```\n\n7. **Command Output**: Shell scripts often store the output of commands in variables.\n\n   ```bash\n   current_directory=$(pwd)\n   ```\n\n8. **Null/Unset**: Represents an uninitialized or unset variable.\n\n   ```bash\n   unset my_var\n   ```\n\nThese are the most common data types used in shell scripting. Keep in mind that shell scripting languages like Bash are loosely typed, meaning variables can change types, and operations often depend on context. For example, a variable that held a string can be modified to hold an integer without explicit type declarations. However, understanding and adhering to data type conventions can lead to more readable and maintainable code in shell scripts.\n\n## Where I use $ for variable and where not? \nIn Bash scripting, you use the `$` symbol to reference the value of a variable. However, there are specific cases where you use `$` and other cases where you don't. Here's a general guideline:\n\n1. **Referencing Variable Values**: When you want to access the value of a variable, you prepend the variable name with `$`. For example:\n   \n   ```bash\n   variable_name=\"Hello\"\n   echo $variable_name\n   ```\n\n   In this example, `$variable_name` is used to access the value \"Hello\" stored in the variable.\n\n2. **Assigning Values to Variables**: When you assign a value to a variable, you don't use `$` on the left side of the assignment. For example:\n\n   ```bash\n   variable_name=\"World\"\n   ```\n\n   Here, `variable_name` is assigned the value \"World\" without using `$`.\n\n3. **Mathematical Operations**: When performing mathematical operations with variables, you use `$` to access the variable values. For example:\n\n   ```bash\n   num1=5\n   num2=3\n   sum=$((num1 + num2))\n   ```\n\n   Here, `$num1` and `$num2` are used to access the values of the variables for addition.\n\n4. **Command Substitution**: When you want to capture the output of a command and store it in a variable, you use `$()` for command substitution. For example:\n\n   ```bash\n   current_date=$(date)\n   ```\n\n   Here, `$(date)` is used to execute the `date` command and capture its output in the `current_date` variable.\n\n5. **String Manipulation**: When you want to concatenate strings or perform other string operations, you use `$` to reference the variable values. For example:\n\n   ```bash\n   first_name=\"John\"\n   last_name=\"Doe\"\n   full_name=\"$first_name $last_name\"\n   ```\n\n   Here, `$first_name` and `$last_name` are used to concatenate the strings into `full_name`.\n\nIn summary, you use `$` to reference variable values, whether you're accessing, manipulating, or assigning values to variables. The `$` symbol indicates to Bash that you are working with the contents of a variable. However, you don't use `$` when declaring or assigning values to variables.\n\n## [\\ is the bash escape character](#is-the-bash-escape-character)\n```bash\n$ ls\nbash.pdf   bash.ppt  'CSE 3128 - Lab1 Lab1_ Introduction to Swift.pptx'   Lab-02.pdf   lab2shellScripting.txt  'OS Lab 1.pdf'   test.sh  '*try.txt'\n\n$ ls \\*try.txt # Using the backslash to escape the asterisk\n'*try.txt'\n\n$ ls '*try.txt' # Using single quotes to preserve the literal value of *\n'*try.txt'\n```\nWhen I mentioned \"escape the asterisk in the filename,\" I was referring to situations where a filename contains a special character like an asterisk (*).\nIn shell scripting, some characters, such as *, have special meanings and are used as wildcard characters for pattern matching. If you have a file with a special character like * in its name and you want to treat that character as a literal part of the filename (i.e., you don't want the shell to interpret it as a wildcard), you can \"escape\" it. Escaping means that you use a special character or sequence of characters to tell the shell to treat the following character as a regular character and not as a special character with its usual meaning.\nIn this case, the backslash tells the shell to treat the * as a regular character and not as a wildcard. This allows you to work with files that have special characters in their names without having those characters interpreted as something else.\n\n## [Single and Double Quote](#Single-and-Double-Quote)\n\n**Using double quotes to show a string of characters will allow any variables in the quotes to be resolved**\n```bash\n$ var=“test string”\n$ newvar=“Value of var is $var”\n$ echo $newvar\n\nValue of var is test string\n```\n\n**Using single quotes to show a string of characters will not allow variable resolution**\n```bash\n$ var=’test string’\n$ newvar=’Value of var is $var’\n$ echo $newvar\n\nValue of var is $var\n```\n\n## [Read command](#Read-command)\n```bash\n#!/bin/bash\nroll_number=115\nstudent_name=\"Azraf Sami\"\necho \"My roll is $roll_number\"\necho \"My name is $student_name\"\n\nread user_input\necho \"You entered =\u003e $user_input\"\n```\n**Another Example**\n\u003e This will delete specific file.\n```bash\n#!/bin/bash\necho -n \"Enter the file name to delete:\"\nread file \necho \"Type 'y' to confirm, 'n' to cancel\"\nrm -i $file\necho \"That was your decision!\"  \n```\n`echo -n \"Enter the file name to delete:\"`\u003cbr\u003e\nThis line uses the echo command to display the message \"Enter name of file to delete: \" to the terminal. The -n option is used to suppress the newline character, so the cursor remains on the same line, allowing the user to input text on the same line as the prompt.\n\u003cbr\u003e\n`rm -i $file` \u003cbr\u003e\nThis line uses the rm command to attempt to remove (delete) the file specified by the value stored in the $file variable. The -i option stands for \"interactive,\" and it prompts the user for confirmation before actually removing the file. If the user types 'y' (yes), the file is deleted; if the user types 'n' (no), the file is not deleted.\n\n## [Command Substitution](#Command-Substitution)\n\n**Using backtick(``)**\n```bash\n#!/bin/bash\nLIST=`ls`\necho \"$LIST\"\n```\n\u003cblockquote\u003e\nOutput: \u003cbr\u003e\nbash.pdf \u003cbr\u003e\nbash.ppt \u003cbr\u003e\nLab-02.pdf \u003cbr\u003e\nlab2shellScripting.txt \u003cbr\u003e\nOS Lab 1.pdf \u003cbr\u003e\ntest2.sh \u003cbr\u003e\ntest.sh \u003cbr\u003e\n\u003c/blockquote\u003e\n\n```bash\n#!/bin/bash\nPS1=\"`pwd`\u003e\"\necho $PS1\n```\n\u003cblockquote\u003e\nOutput: \u003cbr\u003e\n/home/sami/00 3-2\u003e\n\u003c/blockquote\u003e\nIn the command:\n\n```bash\nPS1=\"`pwd`\u003e\"\n```\n\nYou are configuring the `PS1` (Prompt String 1) environment variable in a Bash shell. This variable controls the format and appearance of your command prompt in the shell.\n\nHere's an explanation of the command step by step:\n\n1. `PS1=`: This part of the command sets the `PS1` environment variable, which determines the primary prompt string for your shell.\n\n2. \"`pwd`\": Inside the double backticks (`` ` ``), you have a command substitution. The `pwd` command stands for \"print working directory,\" and it is used to display the current directory path.\n\n3. `\u003e`: This is a character (\u003e) that is included as part of the prompt string.\n\nWhen you set `PS1` to \"`pwd`\u003e\", it means your shell prompt will display the current working directory followed by a greater-than sign (`\u003e`). This is a common way to customize your shell prompt to show you the current directory in your command line.\n\nSo, when you run the command and see `/home/userid/work\u003e _`, it means that you are in the `/home/userid/work` directory, and the `\u003e` character is part of your customized prompt. The underscore (_) represents the cursor position where you can start typing your commands.\n\nCustomizing the `PS1` variable allows you to personalize your shell prompt to display information that you find useful while working in the shell.\n\n**Using $(command)**\n```bash\n#!/bin/bash\nLIST=$(ls)\necho $LIST \n```\n\u003e Output: bash.pdf bash.ppt Lab-02.pdf lab2shellScripting.txt OS Lab 1.pdf test2.sh test.sh\n\n## [Arithmetic Evaluation](#Arithmetic-Evaluation)\n\n**Using let**\n```bash\n#!/bin/bash\nlet X=2*4+5\necho $X\n\nlet Y=10*X-6 \necho $Y \n```\n**Using $ [expression] or $((expression))**\n```bash\n#!/bin/bash\necho “$((123+20))”\n\nVALORE=$[123+20]\necho “$[123*$VALORE]”\n```\n\n## Expressions\n\u003e -d =\u003e check if path given is a directory \u003cbr\u003e\n\u003e -f =\u003e check if path given is a file \u003cbr\u003e\n\u003e -e =\u003e check if file name exists \u003cbr\u003e\n\u003e -r =\u003e check if read permission is set for file or directory \u003cbr\u003e\n\u003e -s =\u003e check if a file has a length greater than 0 \u003cbr\u003e\n\u003e -w =\u003e check if write permission is set for a file or directory \u003cbr\u003e\n\u003e -x =\u003e check if execute permission is set for a file or directory \u003cbr\u003e \n\n\n## Conditional Statements\n- Need to have spaces around [ and ] when using them as part of conditional \u003cbr\u003e\n  statements like if. (keep space like this ==\u003e if`space`[`space`\"$var1\" = \"$var2\"`space`] )\n- Enclosing the variables $name and $USER in double quotes to handle cases where they might contain spaces or special characters.\n\n```bash\n#!/bin/bash\necho -n \"Enter your name:\"\nread name\n\nUSER=\"sami\"\nADMIN=\"admin\"\n\nif [ \"$name\" = \"$USER\" ]\nthen\n\techo \"Hello, $name, you are a general user\"\n\t\nelif [ \"$name\" = \"$ADMIN\" ]\nthen\n\techo \"You are a ADMIN\"\n\t\nelse\n\techo \"Username is wrong\"\nfi \t\n```\n\u003cbr\u003e\n\n**Nested Condition**\n```bash\n#!/bin/bash\n\necho -n \"Enter your age: \"\nread age\n\nif [ \"$age\" -ge 18 ]; then\n    echo \"You are an adult.\"\n\n    if [ \"$age\" -ge 21 ]; then\n        echo \"You are also eligible to vote and purchase alcohol.\"\n    else\n        echo \"You are eligible to vote but not eligible to purchase alcohol.\"\n    fi\n\nelse\n    echo \"You are not an adult.\"\nfi\n```\n\u003cbr\u003e\n\n**Another Example**\n\u003e Checking if file directory exits or not\n```bash\n#!/bin/bash \necho -n \"Enter the path:\"\nread folderPATH \n\nif cd $folderPATH\nthen\n\techo \"Path is $folderPATH and it contains \" ;ls\n\nelse\n\techo \"The directory $folderPATH is not exist\"\n\texit 1\n\nfi\n```\n**********************************************\n\n```bash\n#!/bin/bash\necho -n \"Enter Folder Path:\"\nread folderPATH\nif [ -d \"$folderPATH\" ]\nthen \n\techo \"$folderPATH is exist and it contains\"\n\tls \"$folderPATH\"\nelse\n\techo \"Folder directory is not exist\" \n\texit 1 \nfi \n```\nDon't use `PATH` as variable name because it will generate error. Instead of using `PATH` as variable name, I use `folderPATH` as variable name. \u003cbr\u003e\n\nThe `exit 1` statement in the Bash script you provided is used to indicate an error condition and to exit the script with a non-zero exit status. \u003cbr\u003e\nIn Bash and many other programming languages, it is a common practice to use non-zero exit statuses (typically 1 or higher) to indicate that something went wrong or that an error occurred during script execution. By convention, a script with a non-zero exit status suggests that an error condition was encountered.\n\n## Logical operators\n\u003e ! =\u003e negate (NOT) a logical expression \u003cbr\u003e\n\u003e -a =\u003e logically AND two logical expressions \u003cbr\u003e\n\u003e -o =\u003e logically OR two logical expressions \u003cbr\u003e\n\n```bash\n#!/bin/bash\n\necho -n \"Enter your age: \"\nread age\n\nif [ \"$age\" -ge 18 -a \"$age\" -lt 65 ]; then\n    echo \"You are of working age.\"\nelif [ \"$age\" -ge 65 -o \"$age\" -lt 18 ]; then\n    echo \"You are either a senior or a minor.\"\nelse\n    echo \"Invalid age input.\"\nfi\n```\n\n\u003e \u0026\u0026 =\u003e logically AND two logical expressions \u003cbr\u003e\n\u003e || =\u003e logically OR two logical expressions\n\n```bash\n#!/bin/bash\n\necho -n \"Enter your age: \"\nread age\n\nif [ \"$age\" -ge 18 ] \u0026\u0026 [ \"$age\" -lt 65 ]; then\n    echo \"You are of working age.\"\nelif [ \"$age\" -ge 65 ] || [ \"$age\" -lt 18 ]; then\n    echo \"You are either a senior or a minor.\"\nelse\n    echo \"Invalid age input.\"\nfi\n```\n## Case Statement\n\n```bash\n#!/bin/bash\n\necho \"Choose an option:\"\necho \"1. Say Hello\"\necho \"2. Say Goodbye\"\necho \"3. Say Something else\"\necho \"4. Quit\"\n\nread choice\n\ncase $choice in\n    1)\n        echo \"Hello!\"\n        ;;\n    2)\n        echo \"Goodbye!\"\n        ;;\n    3)\n        echo \"Something else.\"\n        ;;\n    4)\n        echo \"Quitting...\"\n        exit 0\n        ;;\n    *)\n        echo \"Invalid choice.\"\n        ;;\nesac\n```\n\u003cbr\u003e\n\n\u003e Find Even or Odd number\n```bash\n#!/bin/bash\necho -n \"Enter a number:\"\nread num\nremainder=$[$num % 2]\n\ncase $remainder in \n\t0) \n           echo \"$num is even number\";;\n        1)\n           echo \"$num is odd number\";;\n        *) \n           echo \"$num is invalid input\";;   \n esac \n```\n\u003cbr\u003e \n\n\u003e Using \"if\" and \"case\" together\n\n```bash\n#!/bin/bash\necho -n \"Enter a number:\"\nread num\n\ncase $num in \n\t[0-9]* )\n\t    if [ $[$num % 2] -eq 0 ]\n\t    then\n\t    \techo \"$num is a even number\" \n\t    else\n\t    \techo \"$num is a odd number\"\n\t    fi;;\n\t\n\t*) \n\t   echo \"$num is a invalid input\";;\nesac\n```\n## Iteration Statements\n\n### Using For Structure \n\n```bash\n#!/bin/bash\nsum=0\nfor num in 1 2 3 4 5 \n\tdo\n\t  sum=$[$sum + $num] \n\tdone\necho $sum\n```\n\u003cbr\u003e \n\n**Another Example:**\n```bash\n#!/bin/bash\nfor name in Sk. Azraf Sami\n\tdo \n\t   echo \"My name is $name\"\n\t   sleep 1\n\t done\n```\n\u003cbr\u003e \n\n\u003e If the list part is left off, var is set to each parameter passed to the script ( $1, $2, $3,…)\n```bash\n#!/bin/bash\nfor var\n\tdo \n\t   echo \"The value of variable 'var' is $var\"\n\t   sleep 1\n\t done\n# $ chmod +x test.sh\n# $ ./test.sh arg1 arg2\n\n# Output:\n# The value of variable 'var' is arg1\n# The value of variable 'var' is arg2\n\n```\n### C-like for loop\n```bash\n#!/bin/bash\necho -n \"Enter a number:\"\nread num\nsum=0\nfor((i=1 ; $i \u003c= $num ; i=$i+1))\n\tdo\n\t  sum=$[$sum+$i]\n\tdone\necho \"The sum of the first $num is: $sum\"\n```\n### While Statements\n\n```bash\n#!/bin/bash\necho -n \"Enter a number:\"\nread num\n\nsum=0\ni=1\n\nwhile [ $i -le $num ]\n\tdo \n\t  sum=$[$sum+$i]\n\t  i=$[$i+1]\n\tdone\n\necho \"The sum of the first $num is: $sum\"\n```\n## Continue Statements\n## Unix / Linux - Special Variables \nImportant link: https://www.tutorialspoint.com/unix/unix-special-variables.htm \u003cbr\u003e \n\n**Example-1**\n```bash\n#!/bin/sh \n\n# Comment 1: Check if no command line arguments were provided.\nif [ $# -eq 0 ]\nthen\n    echo \"Usage: $0 ordinary_file\"\n    exit 1\nfi\n\n# Comment 2: Check if more than one command line argument was provided.\nif [ $# -gt 1 ]\nthen\n    echo \"Usage: $0 ordinary_file\"\n    exit 1\nfi\n\n# Comment 3: Check if the provided argument is a regular file.\nif [ -f \"$1\" ]\nthen\n    filename=\"$1\"\n    set `ls -il $filename`\n    inode=\"$1\"\n    size=\"$6\"\n    echo \"Name\\t| Inode\\t| Size\"\n    echo\n    echo \"$filename\\t| $inode\\t| $size\"\n    exit 0\nelse\n    echo \"$0: argument must be an ordinary file\"\n    exit 1\nfi\n```\nRun this shell: \n```bash\n$ chmod +x demo_1  # Make the script executable\n$ ./demo_1 sample.txt\n```\nOutput: \n```bash\nName    | Inode  | Size\n\nsample.txt  | \u003cinode_number\u003e | \u003cfile_size\u003e\n```\n\nThe `ls -li` command is used to list information about files and directories in a directory. Here's what each part of the command means:\n\n- `ls`: This is the command to list files and directories.\n- `-l`: This is an option for `ls`, which stands for \"long format.\" When used with `-l`, `ls` provides detailed information about files and directories, including permissions, ownership, size, modification date, and more.\n- `-i`: This is another option for `ls`, which stands for \"inode.\" When used with `-i`, `ls` displays the inode number of each file or directory. The inode number uniquely identifies a file or directory on a filesystem.\n\nSo, `ls -li` combines these two options to list files and directories in long format (`-l`) and display their inode numbers (`-i`).\n\nTo get a list of the meanings of positional parameters in a shell script, you can use the `set` command without any arguments. Here's how you can do it:\n\n```bash\n#!/bin/bash\n\n# Output the positional parameters\necho \"Positional Parameters:\"\necho \"\\$1: $1\"\necho \"\\$2: $2\"\necho \"\\$3: $3\"\n# ... and so on for other positional parameters\n\n# Use the set command to list all positional parameters\necho \"All Positional Parameters:\"\nset\n```\n\nIn this script, `$1`, `$2`, `$3`, and so on represent the individual positional parameters, and the `set` command without arguments lists all positional parameters. When you run the script with arguments, you'll see their values in the output. \u003cbr\u003e \n\n**Example-2**\n\u003cbr\u003e\nchange the code of Example-1 \u003cbr\u003e\n• Change1：When the input parameter represent directory, list the directory’s name, inode, size and owner. The result of directory has the same result as file. \u003cbr\u003e\n• Change2：Show what the parameter represents, file or directory. \u003cbr\u003e \n```bash\n#!/bin/sh \n\nif [ $# -eq 0 ]\nthen\n    echo \"Usage: $0 ordinary_file_or_directory\"\n    exit 1\nfi\n\n# Check if the provided argument is a regular file or directory.\nif [ -e \"$1\" ]\nthen\n    target=\"$1\"\n    if [ -f \"$target\" ]\n    then\n        # It's a regular file.\n        echo \"It's a regular file\"\n        set `ls -il $target`\n        inode=\"$1\"\n        size=\"$6\"\n        echo \"Name\\t| Inode\\t| Size\"\n        echo\n        echo \"$target\\t| $inode\\t| $size\"\n    elif [ -d \"$target\" ]\n    then\n        # It's a directory.\n        echo \"It's directory\"\n        set `ls -il $target`\n        inode=\"$1\"\n        size=\"$6\"\n        owner=\"$3\"\n        echo \"Name\\t| Inode\\t| Size\\t| Owner\"\n        echo\n        echo \"$target\\t| $inode\\t| $size\\t| $owner\"\n    else\n        echo \"$0: argument must be an ordinary file or directory\"\n        exit 1\n    fi\nelse\n    echo \"$0: argument does not exist\"\n    exit 1\nfi\n```\n## Practice More Problems: \n - HackerRank: https://www.hackerrank.com/domains/shell \u003cbr\u003e\n\n## More Tutorials: \nhttps://www.geeksforgeeks.org/linux-tutorial/ \u003cbr\u003e \nhttps://www.tutorialspoint.com/unix/index.htm \u003cbr\u003e \n\n## Real Life Problems: \n\n**Move same extension files from one folder to another folder**\n```bash\n#!/bin/bash\n\nsource_folder=\"/home/sami/Downloads\"\ndestination_folder=\"/home/sami/Downloads/00mhtml\"\n\nif [ ! -d $source_folder ]; then \n   echo \"Source folder does not exist!\" \n   exit 1 \nfi \n\nif [ ! -d $destination_folder ]; then \n   mkdir -p $destination_folder\nfi\n\nsudo mv \"$source_folder\"/*.mhtml \"$destination_folder/\"\n\nif [ $? -eq 0 ]; then \n   echo \"All files are moved from $source_folder to $destination_folder\"\n\nelse \n   echo \"No mhtml file found in the $source_folder\"\n\nfi \n```\n\nIn shell scripting, `$?` is a special variable that stores the exit status of the last executed command. It typically holds an integer value, where `0` usually indicates success or that the previous command completed without errors, and a non-zero value indicates some kind of error or failure.\n\nSo, when you see `$? -eq 0`, it's a conditional statement that checks if the exit status of the previous command is equal to `0`. If it is, it means the previous command executed successfully, and the condition evaluates to true. If the exit status is not `0`, it means there was an error or failure, and the condition evaluates to false.\n\nHere's a breakdown:\n\n- `$?`: Represents the exit status of the last command.\n- `-eq`: This is a comparison operator that checks if two values are equal.\n- `0`: The value to which the exit status is compared.\n\nSo, `$? -eq 0` essentially means \"check if the exit status of the last command is equal to 0,\" which is a common way to verify if a command completed successfully in a shell script.\n\n⚠️  Some of my mhtml files not move to 00mhtml and they are not exist in source folder either. Where they are gone? \u003cbr\u003e \n\nIn your script, you are using the `sudo mv` command to move all files with the `.mhtml` extension from the source folder to the destination folder. However, some of the files might not have been moved for the following reasons:\n\n1. **Permissions:** If some files in the source folder do not have read permissions for the user running the script, the `sudo mv` command won't be able to read and move those files.\n\n2. **File Names:** It's possible that some files in the source folder have special characters or file names that are not supported by the `mv` command. These files might not be moved as expected.\n\n3. **Errors in Source Folder:** There could be errors in the source folder path or the source folder might not contain the expected `.mhtml` files.\n\nTo troubleshoot this issue, you can do the following:\n\n1. **Check Permissions:** Verify the permissions of the files in the source folder. You can use the `ls -l` command to list the files and their permissions. Ensure that the user running the script has read permissions for all the `.mhtml` files.\n\n   ```bash\n   ls -l /home/sami/Downloads/*.mhtml\n   ```\n\n2. **Check File Names:** Check if any of the files in the source folder have special characters or file names that could cause issues with the `mv` command.\n\n3. **Check Source Folder Contents:** Verify that the source folder indeed contains the `.mhtml` files you expect to move. You can use the `ls` command without any filters to list all files in the folder.\n\n   ```bash\n   ls /home/sami/Downloads\n   ```\n\n4. **Error Handling:** Modify your script to include better error handling and reporting. For example, you can use `rsync` or `cp` instead of `mv` to copy the files and then remove them from the source folder only if the copy was successful. This way, you can avoid losing files.\n\nHere's an example of how you can modify your script using `rsync`:\n\n```bash\n#!/bin/bash\n\nsource_folder=\"/home/sami/Downloads\"\ndestination_folder=\"/home/sami/Downloads/00mhtml\"\n\nif [ ! -d \"$source_folder\" ]; then \n   echo \"Source folder does not exist!\" \n   exit 1 \nfi \n\nif [ ! -d \"$destination_folder\" ]; then \n   mkdir -p \"$destination_folder\"\nfi\n\nrsync -a --remove-source-files \"$source_folder\"/*.mhtml \"$destination_folder/\"\n\nif [ $? -eq 0 ]; then \n   echo \"All files are moved from $source_folder to $destination_folder\"\nelse \n   echo \"No mhtml file found in the $source_folder\"\nfi\n```\n\nThis modified script uses `rsync` with the `--remove-source-files` option to copy and remove files only if the copy operation was successful. This helps prevent the loss of files during the move operation.\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsk-azraf-sami%2Fbasic-shell-programming","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsk-azraf-sami%2Fbasic-shell-programming","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsk-azraf-sami%2Fbasic-shell-programming/lists"}