#!/வாங்க/Bash/படிக்கலாம்
Published: 2023-10-02 13:37:21

### **What is Bash ?**
- Its a Unix Shell & Command Language.
- Also default command interpreter on most Linux systems.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uxa5pjuza76vcrc7hydp.png)

Bash என்றால் என்ன என்று சொல்லிட்டீங்க , but what is **_shell_** here ?
- Shell is a UNIX term for the interactive user interface with an operating system. The shell is the layer of programming that understands and executes the commands a user enters. In some systems, the shell is called a command interpreter.
- A Shell provides you with an interface to the Unix system. It gathers input from you and executes programs based on that input. When a program finishes executing, it displays that program's output.
- Shell is an environment in which we can run our commands, programs, and shell scripts. There are different flavors of a shell, just as there are different flavors of operating systems. 
- Each flavor of shell has its own set of recognized commands and functions.

இவ்ளோ இருக்குன்னு பாக்காதீங்க இது எல்லாமே சின்ன சின்ன definitions  which will be useful for interview.
- Bash stands for Bourne-Again SHell.
- As with other shells, you can use Bash interactively directly in your terminal, and also, you can use Bash like any other programming language to write scripts.
- Bash scripts are great for automating repetitive workloads and can help you save time considerably.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txmog6oo2jpht8jsb6f2.png)

இப்ப உங்க projectல மொத்தம் ஒரு ஆறு பேர் இருக்கீங்க,  அந்த ஆறு பேரும் ஒரே Java environment  install  பண்ணனும்.  ஒரு ஒரு machineல போய் பண்றதை விட , இதை நீங்க ஒரு script எழுதி , அந்த script ஓட்டிவிட்டா எல்லாம் machineல install ஆயிடும் இல்ல.

- We can use any Text editor like Sublime Text, VS Code, or a terminal-based editor like vim or nano for writing a Bash script.

### NOW LET'S FALL INTO BASH SCRIPT

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y8m650gg01dfue5s0ebi.png)
```
touch devdojo.sh
nano devdojo.sh
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbbvra6zogvmz6j85g5c.png)

> If you want to execute this bash script file with the bash shell interpreter , so we need to indicate the **absolute** path of the bash.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79spjf78qg85jxjxgcqd.png)
```
#! interpreter [optional-arg]
```

> A **_shebang_** is the character sequence consisting of the characters number sign and exclamation mark (#!) at the beginning of a script.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1jct5nuveoaxqydfwia.png)
Shebang என்ன சொல்லுதுன்னா , OS  கிட்ட  இது ஒரு bash shell scriptனு சொல்லுது  அவ்வளவுதான்.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dzzxmg02d60v2xxrxreh.png)

> இப்ப இந்த fileல executableலா மாத்தணும்

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b90qk73t209bf59w93gj.png)

> Both ways we can run the script

```
./devdojo.sh
bash devdojo.sh
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2q0gal8zsszswy2f24y.png)

> In Bash there is **_no data types_** BUT we can use **_variables_** ( it can also contain numbers too )

```
name="devops"
echo $name
echo ${name} --> Good Practice to use "{}"

Important : We can't have spaces before and after the "="
sign.
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a42yfwx60nkr2ypulefh.png)

```
#!/bin/bash
name="devops"
echo "I am learning ${name}"
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i68dlnzv4kdibtm3w8zq.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o1mrl65t8i2gcjhio9ma.png)

> **A quick review or rundown**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jdum2swcgw6o2ibcg6r.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6oym6orxmstoh1cpyydj.png)

<u>**Test with passing arguments :**</u>

> Two arguments

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eesx64um1uz7tu7f0mvg.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhbu7or5nz8pqu3k24sh.png)

> Read from User Input

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6ilvbuvz5349q4v4g03.png)

```
echo "what are you learning?"
read name
echo "He is learning $name"
echo "welcome to current technology"
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0jljy9a508cw6evoj8pr.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cgh3lrcn063zeztbjc6.png)

Input கொடுத்தோம் இல்ல ,  அந்த value எடுத்துக்க **READ** ஆபரேஷன் use பண்ணனும்.

> Codeஅ இப்ப reduce பண்ண போறோம்

```
read -p "what are you learning?" name
echo "He is learning $name"
echo "welcome to current technology"
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p4y0u9uy39lo8or4raj3.png)

echo ---> read -p
**_The read command used with -p flag will print a message before prompting the user for their input._**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ltdo2r7pddpam4o1f03.png)

```
# This is a comment and will not be rendered on the screen
```
> Why we are commenting using "#" ? 

Code  உனக்கு மட்டும் புரிஞ்சா பத்தாது மத்தவங்களுக்கும்  புரியணும் . அதுக்கு தான் நம்ம COMMENTS # யூஸ் பண்றோம்.

#### <u>INFO 1</u> : **_$1_** --> First Argument , **_$2_** --> Second Argument , **_$3_** --> Third Argument , அப்ப $0  எங்க போச்சு ?  இது ஒரு  வாஸ்தவமான பேச்சு . **$0** is used to reference the script itself.

```
#!/bin/bash
echo "The name of the file is: $0 and it is going to be selfdeleted."
rm -f $0
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n23cett24ebjd8dxs9wl.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbg88rgiz2py5cncrxll.png)

நல்ல Note பண்ணுங்க அந்த rm command கொடுத்ததினால் அந்த file delete ஆயிடுச்சு பாருங்க.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i05j46x1mg5b9vyvgo34.png)

We need to be careful with the self deletion and ensure that you have your script backed up before you self-delete it.

### ARRAYS

> Arrays can hold several values under one name

- Initialize an array by values divided by **space** and enclosed by **()**.
- Using @ will return all arguments in the array.
- Prepending the array with a hash sign **(#)** would output the total number of elements in the array.

```
#!/bin/bash
my_array=("cat" "dog" "fish" "elephant")
echo ${my_array[1]}
echo ${my_array[2]}
echo ${my_array[-1]}
echo ${my_array[@]}
echo ${#my_array[1]}
echo ${#my_array[@]}
name=("sathishpy1808")
echo "${#name[0]}"
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vu17sw7rds8cm4ir35xi.png)

### SLICING IN A STRING
```
#!/bin/bash

alphabets=("A""B""C""D""E")

#print all the elements of an array
echo ${alphabets[@]}

#print array from starting index 0 to 2 where 2 is exclusive
echo ${alphabets:0:2}

#will print from base index 0 to 5, where 5 is exclusive and starting index is default set to 0
echo ${alphabets::5}

#print from starting index 3 to end of array inclusive
echo "${alphabets:3}"
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uq6nti39zqutptnwy7x6.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2e9bamafnqjrruhg9fk.png)

**_alphabets=("A""B""C""D""E")
alphabets=("A" "B" "C" "D" "E")_** --> In this SPACE will be counted , so be cautious in providing the values in a array while using Slicing.

### CONDITIONAL EXPRESSIONS

- Conditional expressions are used by the **_[[_** compound command and the **_[built-in_** commands to test file attributes and perform string and arithmetic comparisons.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3olw3dwhn4s2fbc2c7cm.png)

- **_True_** if the strings are equal. **_=_** should be used with the test command for POSIX conformance. When used with the [[ command, this performs pattern matching as described above (Compound Commands).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1y2ii1t3ipq1fp4n98o.png)

### CONDITIONAL EXPRESSIONS

- use "CONDITIONAL EXPRESSIONS" in if, if-else and
switch case statements.

<u>Syntax or Format :</u>

```
if [[ some_test ]]
then
 <commands>
fi
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ycmjlvalpaak26or93v.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xpi7nvrr7q1ctvz2dbo.png)

```
#!/bin/bash

# IF statement example

read -p "Enter the name: " name
if [[ -z ${name} ]]
then
        echo "PLEASE enter your name"
fi
```
> With ELSE

```
#!/bin/bash

# IF statement example

read -p "Enter the name: " name
if [[ -z ${name} ]]
then
	echo "PLEASE enter your name"
else
	echo "Welcome $name"
fi
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdv7qqzmlptsyz9cg5uo.png)

> With conditional expressions

```
#!/bin/bash

# IF statement example

name1="devops"

read -p "Enter the name: " name

if [[ ${name} == ${name1} ]]
then
	echo "YOUR name is correct"
else
	echo "Requesting to CHECK your name"
fi
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/td14od1s5dfjkzt1jkie.png)

**<u>INFO 2:</u>**

- An if statement which would check your current UserID and would not allow you to run the script as the root user.
- If you put this on top of your script it would exit in case that the EUID is 0 and would not execute the rest of the script.

```
#!/bin/bash
if [[ $EUID == 0 ]]; 
then
 echo "Please do not run as root"
 exit
fi
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tf83ymjicwq0cl6vbjd.png)

> With Multiple Conditions

- In this example we want to make sure that the user is neither the admin user or the root user to ensure the script is incapable of causing too much damage. 
- We'll use the or operator in this example, noted by ||. This means that either of the conditions needs to be true. If we used the and operator of && then both conditions would need to be true.

```
[TBD]

#!/bin/bash
admin="sathishpy1808"
read -p "Enter your username? " username

# Check if the username provided is the admin

if [[ "${username}" != "${admin}" ]] || [[ $EUID != 0 ]] ;
then
 echo "You are not the admin or root user, but please be
safe!"
else
 echo "You are the admin user! This could be very
destructive!"
fi
```

> With Multiple Conditions avec **elif**

gt ---> greater than
lt ---> lesser than

```
#!/bin/bash
read -p "Enter a number: " num
if [[ $num -gt 0 ]] ; then
 echo "The number is positive"
elif [[ $num -lt 0 ]] ; then
 echo "The number is negative"
else
 echo "The number is 0"
fi
```

> Case Statement


[ TO BE CONTINUED ... ]




### LINUX COMMANDS

- Daily இந்த command எல்லாம் use பண்ணி  பாருங்க , அப்பதான் mindல நிக்கும் -  நான் சொல்லல என் professor சொன்னாரு .

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rnfys0bmmn9iqrseizyu.png)



## IMPORTANT NOTES:

1. https://www.shellcheck.net/  --->  Way to test your scripts is to use this fantastic tool. ( https://github.com/koalaman/shellcheck )

2. **set -x** (or) **bash -x ./your_script.sh** ---> Enable debug mode.

3. https://www.digitalocean.com/community/questions/what-are-your-favorite-bash-shortcuts

4. https://www.digitalocean.com/community/questions/how-to-check-if-running-as-root-in-a-bash-script