Bash Tutorials ==================================================================================================== Explore Bash shell scripting tutorials and programming examples.. This post provides tutorials on Bash commands and programming with examples. The course covers Bash and shell programming features, including variables, loops, conditional expressions, and operators. Shell is a command-line interpreters, It is an application to provide commands to the different operating systems such as Linux, Unix, and Mac. Bash is an enhanced version of shell, an layer between user and operating system function calls. User types the commands via command line or batch of commands also called scripts. Requirement To follow this course, you should have a basic understanding of computer language, and the following are required: * Linux-flavored operating system * Basic knowledge of any programming language What is Bash Bash, short for Bourne Again Shell, is an open-source command-line shell interpreter and scripting language. It interprets user-entered commands, either interactively or from a script file. It serves as an interface to call commands, enabling system function calls. Threre are two types of bash modes * Interactive mode: Also called a command interpreter, it allows the execution of commands in the terminal. It executes commands sequentially if there are multiple commands. * Non-interactive mode: This refers to scripts, allowing you to write Bash syntax that contains a sequence of multiple commands for script execution. What is the difference between Bash and shell Shell, an alias for Bourne Shell, is a command-line interpreter for Unix and Linux OS. Bash, an alias for Bourne Again Shell, is an enhanced version. What is bash scripting used for? Bash scripting has multiple use cases, including: * Writing scripts to automate programming tasks * Synchronizing tasks to copy files * Executing cron jobs for scheduling How do I write code in bash? To write code in a Bash script, follow these steps: 1. In the terminal, create a file using vi test.sh. 2. Add #!/bin/bash at the top of the file. 3. Add multiple shell code snippets. 4. Save the shell file with a .sh extension. 5. Execute the shell script using the ./test.sh command in the terminal. Is bash coding language? Bash executes commands from the terminal or a file. It is a programming language that operates in Unix/Linux kernel operating systems, containing all the features to write complete code. Bash is a special type of shell that takes input from commands, runs the code, and processes the input, returning results. Shell Types There are different types of shells in a Unix OS. Shell Type Alias First Line sh Bourne Shell #!/bin/sh bash Bourne Again shell #!/bin/bash cshell C shel #!/bin/csh Difference between Command Line and Script in bash Let’s see the difference between command line and scripts Commands line options * Command line has a prompt which takes input from a user * Commands are not saved to a file. * It supports only one command at a time. Script files * Support multiple commands in a single file * Prompt still can be written in the script file * Only one line in a file executes sequentially Bash - Variables ==================================================================================================== Learn how to declare and use variables in bash scripts. Types of global, local, and readonly variables, and understand proper syntax for accessing variables in shell scripts.. This post is about how to bash commands and programming tutorials with examples. Bash Shell Variable Variables form the fundamental building blocks of any programming language. Shell and bash script programming offer variables, much like other languages. A variable serves as a container used for storing data in programming. It includes a pointer to the memory location of the data. Declare variable: To create a variable, you must assign a value to it. variableName=VariableValue variableName: It is the name of the variable, which can contain any combination of alphabets (a to z, A to Z), numbers (0 to 9), and underscores (_). VariableValue is the value stored in a variable, and it can be a string of numbers or a boolean. The equal symbol (=) is used to assign a value to a variable. For example AGE=25 A variable named AGE is created and assigned the value 25. How to Access Variables in Bash After declaring and assigning values to variables, you can access them using a dollar symbol ($) followed by the variable name. AGE=25 echo $AGE This above code declares a variable named AGE with a value of 25 and then uses echo to display the value of the AGE variable. The dollar symbol before the variable name is crucial for accessing its value. Bash Shell Readonly Variables Once variables are assigned values, you can change them to new values using the assignment operator =. AGE=25 echo $AGE AGE=35 echo $AGE Output: 25 35 How do you make variables not updatable? The readonly keyword prevents a variable from being updated, effectively turning it into a constant. AGE=25 echo $AGE readonly AGE AGE=35 echo $AGE AGE is an constaints, assigning new value throws an error , and the error message is AGE: is read-only. Output: 25 line 6: AGE: is read-only Bash unset variable The unset keyword assists in removing the value from the specified variable. The variable remains accessible but prints an empty value. AGE=25 echo $AGE unset AGE echo "empty":$AGE Output: 25 empty: Above code, * first sets the variable AGE to 25, prints its value, * then unsets it using unset AGE. * Subsequently, it prints “empty” followed by the value of AGE, which now appears as empty space. Variable Scopes Every declared variable must have a scope, defining where in the program the variable can be used. For instance, if a variable is declared within a function, it is available only within that function and is not accessible outside of it. Variable scopes in Bash can be defined in two ways * Global variable * Local variable: Bash Global Variables Variables declared in a shell script are referred to as global variables. Global variables can be accessed within a function or any nested blocks of a shell script file. The default variable declared in a script file is called a global variable. setAge() { echo "Inside Function Age: $AGE" } AGE=40 setAge echo "Script Age: $tmp" Output Inside Function Age: 40 Script Age: 40 Bash Local variables Local variables are declared inside a block of code or a function. The scope of these variables is visible only within the block where they are declared. Syntax: local variablename=variablevalue In this syntax, the variable is declared and assigned with the local keyword. setAge() { local AGE=25 echo "Local Variable Age: $AGE" } AGE=40 setAge echo "Global Age: $tmp" Output Local Variable Age: 25 Global Age: 40 A local variable is declared inside a function and is only visible within that function. Variables declared outside functions are called global variables and are available for all functions. Variables typing Bash scripting is not typed language, however you can declare an variable with a type of the data using declare command Based on the type of variable, it allows the type of the data . declare options variablename=value variable is declared and assigned with a value. Options contains option to create a type of a varialbe Array: To create an array variable declare -a variable= Variable Type Syntax Description Array declare -a variable declare an indexedarray variable that stores strings Associated Array declare -A variable Associated Array Integer declare -i variable numeric value to store in variable Readonly declare -r variable readonly variable, cannot be changed or unset Export declare -x variable export the variable and used by all child process Display Environment variables in Bash In Bash, there are two types of commands for printing environment variables. * The printenv command * The env command Both of these commands list all the environment variables of the terminal. Variable nameing convention * Variables are read by prefixing with the $ symbol. * Variable names are composed of alphabets, numbers, or underscores. * Variables are case-sensitive; for example, test and Test are considered two different variables in scripting. * While variable names are conventionally written in UPPERCASE, you can create them using UPPER or LOWER case if needed. And Environment and Shell variables are both in UPPERCASE. * Variable names can not contain spaces * Names conventinaly should be camelCase. Example firstName Shell variables Shell variables are variables are set by the shell, not by the user. These are required by shell to work smoothly Variable Description PWD Current working directory Set-Location Change the working directory to new directory Rename-Item Rename a file IFS Internal FIeld Separator by default is space, set by Shell, Used for string split PATH Contains semicolon separated path of commands, Configured to lookup for commands UID Prints the User Identifcation number Home Home directory of a current user Bash - Loop File ==================================================================================================== How to loop contents of a file in Bash Shell scripting tutorials and programming examples. Sometimes, You want to read the file content with bash programming. There are multiple ways we can do How to read a file by line in bash shell? * using while loop #!/bin/bash while IFS= read -r line; do echo "$line" done , >=, ==, !=) a=10 b=2 if ((a > b)); then echo "a is greater than b" fi * Logical Operators * Conditional Statements Bash Athematic Expansion Expansion are same as expressions, It calculates the value of an expression and result is replaced with an value. It always prefixed by dollar sign. $((expression)) For example, calculate the average of two numbers, print the result. Here used expansion syntax, It evaluates expression and result is replaced with an output of expression. first=12 second=2 echo "The average is $(((first+second)/2))". When to Use arthematic expressions and expansions [[]] is used to test an expression, returns boolean value(1 or 0). This will be used in the following cases * * Use artheatic expression + To perform mathematicl operations and comparision * Use artheatic expression [[] + Comparision of strings and numbers + Check file or directory exists Bash - Functions Bash scripting tutorial on programming examples for concatenating string variables using simple append and shorthand arithmetic operator. Functions are reusable code that can be grouped under a single name. Declare a function Calling a Function Function with arguments Variable scope in Functions How to declare a Function and call it Function defination contains the multiple lines of code to executes. Functions contains a name of a function enclosed in {}. It Can be declare in two ways function function_name { # Commands or valid bash code # multiple lines } function function_name() { # Commands or valid bash code # multiple lines } How to pass a parameters to an function function_name "parameter1" "parameter2" "parameter3".. "parametern" Parameters can be access using $1 $2 $3.. $n function function_name() { # $1 represents first paramter # $2 represents second paramter # $n represents nth paramter } Variable scope inside a function Bash - Append String ==================================================================================================== Learn Bash scripting with practical examples of how to concatenate string variables using both simple append and shorthand arithmetic operators.. In this tutorial, you will learn various methods for appending string variables in Bash. There are multiple ways to append one string to another. Simple variable append Begin by declaring two string variables in the Bash script, which can be printed to the console using echo by enclosing the variables in double-quotes. string1="Hello, " string2='Welcome to w3schools.' echo "$string1 $string2 " You can also append without double quotes echo $string1 $string2 Output: Hello, Welcome to w3schools. Another example involves concatenating a string to the same variable and printing it to the console: result="My site is" result="${result} w3schools" echo "${result}" Output: My site is w3schools This approach has pros and cons * It is simple and easy to append strings. * If you are appending multiple variables, it is less in terms of readability. * Understanding the syntax may be initially difficult for new Bash users. Use Shorthand Arithmetic Operator The shorthand arithmetic operator (+=) is commonly used in arithmetic to add a value to a variable. It can also be used for strings to append a string to a variable. For example. * a+=1 is equivalent to a=a+1 in the case of numbers. * str+="test" will become str=str+"test" in the case of strings. Here is an example code nums="One Two" nums+=" three" echo "$nums" Output: One Two three Notes: * Easy to append strings and readable, as arithmetic operators exist in every language. * Not recommended and inefficient for larger strings. Use printf command printf is used to format strings with various complex formatting options. We can use the printf command to concatenate strings. The format is %s%s, which appends two string variables. str1="Hello, " str2='Welcome to w3schools.' output=$(printf "%s%s" "$str1" "$str2") echo $output Notes: It is not easy to understand the printf with formatted options * Not easy to understand with the printf formatted options. * Not recommended and inefficient for string append. * Less readable for developers. Using here string Here strings are a special syntax to pass a string to a command in a Bash script. They are used to pass an input string without using other sources, such as files. It allows passing a string to any Bash command from a file or a command line. Syntax: command <<< string command: valid command <<<: is a here string operator string is the input string Here is an example first="first " second" second" output="$first$(<<<" $second")" echo $output In this example, the second string is appended to the first string using the here string operator. Notes: * Another way to append strings simply. * This approach is useful for passing strings to commands from a file or the command line only, even though it serves to append a string, it is less readable. Conclusion In this tutorial, you have learned how to concatenate string variables in multiple ways. * Simple variable append and arithmetic operator(+=) are utilized for basic and straightforward string concatenation. * If you require more complex string processing alongside concatenation, printf is recommended. Bash - Operators ==================================================================================================== Supported Operators in Bash scripting programming examples for Logical, Bitwise, Comparision arithmetic operator. What is an operator? Operator is an symbol in programming that performsn an operation on operands Syntax operand1 operator operand2 There are two types of operators. * Binary Operator: It operates on two operands such as addition, subtraction, multiplication, division, and modulus * unary operator: It operats on single operand such as increment and decrement Bash Arithmetic Operators Arithmetic operators in Bash provide arithmetic operations such as add, division, subtraction, and division multiplication operators. Operator Title Description Example + Addition addition of two or more operands p+q=50 - Subtraction subtraction of two or more operands q-p=10 * Multiplication multiplication of two or more operands p*q=600 / Divide results quotient after the division of values q/p=1.5 % Modulus Return the remainder after the division of values q%p=10 % Modulus Return the remainder after the division of values q%p=10 -expr Unary Minus reverse of an expression -(10-7) is -3 ~/ Division Int returns division int value (10~/7) is 1 ++ Increment Increment the value by 1 ++p=21 -- Decrement Decrement the value by 1 --q=29 Here is an arithmetic operator example Assignment Operators Assignment operators are used to assign the values to an variables. The basic operation is equal(=) Additionally, THere are other assignment operators. for example, p is 20 Operation Symbol Description Result Add Assign += Addition and assignment to variable ((p += 3)) is 23 Substract Assign -= Substract and assignment to variable ((p -= 3)) is 17 Multiplicate Assign *= Multiplicatie and assignment to variable ((p *= 2)) is 40 Division Assign /= Addition and assignment to variable ((p /= 5)) is 4 Bitwise Operators Operation Symbol Description Result AND & Bitwise AND of two operands $op1 & $op2 is 0 AND Equal &= Bitwise AND Equal of two operands $op1 & $op2 is 0 OR | Bitwise OR of two operands $op1 | $op2 is 7 XOR ^ Bitwise XOR of two operands $op1 ^ $op2 is 7 Left Shift << Bitwise Left Shift of two operands $op1 & $op2 is 0 Left Shift Eql <<= Bitwise Left Shift Equal of two operands $op1| $op2 is 7 XOR ^ Bitwise XOR of two operands $op1 ^ $op2 is 7 XOR ^= Bitwise XOR Equal of two operands $op1 ^ $op2 is 7 Logical operators These operators are used to perform logicaton operations on variables/expressions/data. Operation Symbol Description Result Logical AND && Return true(exit status=0) if both operands are true, else return false(exit status is non zero) $op1 &&& $op2 is 0 Logical OR || Logical OR of two operands $op1 & $op2 is 0 Logical NOT \! Reverse the conditional value. $op1 s 7 Here is an example String Comparision Operator Operation Description -z String Return true if string is empty, else false. -n String REturn true, If string is not empty str1=str2 return true, if str1 and str2 are equal str1!=str2 return true, if str1 and str2 are not equal str1>str2 return true, if str1 sorts before str2 str1