---
# System prepended metadata

title: L5. Bash Scripting. Part 3

---

# L5. Bash Scripting. Part 3

## Read parameters
* $0 is the script’s name.
* $1 is the 1st parameter.
* $2 is the 2nd parameter.

```bash=
#!/bin/bash
echo $0 # Script name
echo $1 # 1st parameter
echo $2 # 2nd parameter
echo $3 # 3rd parameter
```

```bash=
./myscript 5 10 15
```

```bash=
#!/bin/bash

total=$(( $1 + $2 ))
echo First passed parameter is $1.
echo Second passed parameter is $2.
echo Total is $total.
```
```bash=
$ ./myscript 5 10
```

---

## Check parameters
```bash=
#!/bin/bash
if [ -n "$1" ]; then # If first parameter passed then print Hi
	echo Hi $1.
else
	echo "No parameters found. "
fi
```

---

## Iterate over parameters
:::info
$# : How many parameters passed
${!#}
$* : holds all the parameters as one value
$@ : holds all the parameters as separate values so that you can iterate over them.
:::

---

## Getting user input
```bash=
echo -n "What's your name: "
read name
echo "Hi $name,"
```
```bash=
#!/bin/bash
read -p "What's your name: " first last
echo "Your data for $last, $first…"
```
```bash=
#!/bin/bash
read -p "What's your name: "
echo Hello $REPLY,.
```

#### Reading password
```bash=
#!/bin/bash
read -s -p "Enter password: " mypass
echo "Your password is $mypass? "
```

---

## Read files
```bash=
#!/bin/bash

while read line; do

	echo $line

done <myfile
```

```bash=
#!/bin/bash

count=1

# Get file content then pass to read command by iterating over lines using while command

cat myfile | while read line; do

	echo "#$count: $line"

	count=$(($count + 1))

done

echo "Finished"
```