Skip to main content

Bash Scripting

Read user input

Storing her user input into name variable

echo -n "Enter your name: "
read name
echo "You have entered: $name"

-n flag in echo removes the carriage return


read -p 'username: ' user_name
echo "username is: $user_name"

-p flag in read will remove the carriage return


Hiding input

read -sp 'password: ' password
echo "Your password is: $password"

-sp flag input is hidden


array variable

echo "Enter array names"
read -a names
echo "Names : ${names[0]}, ${names[1]}"

-a flag indicates the names variable an array


array length

echo "The length : ${#names[@]}"

#name[@] returns length of the array


Passing args

Accessing command line args passed to the script

echo "$0 $1 $2 $3"

Storing args in the array

echo 'storing args in the array'
args=("$@")

# Doesn't throw an error if only 2 args are sent 2,3,4 will be empty
echo ${args[0]} ${args[1]} ${args[2]} ${args[3]} ${args[4]}
echo "To print all the args \"\$@\" $@"

Number of args

echo $#

If then elif

#!/bin/bash

echo "***This is if-then-else***"
echo
read -p 'Enter a value: ' var
echo you have entered $var
if [[ $var == 10 ]]
then
echo **The values are equal to 10
elif [[ $var == 100 ]]
then
echo ***The values are 100
elif [[ $var == "abcd" ]]
then
echo Checking \$var == $var
elif [[ $var -eq "Hello" ]]
then
echo Checking \$var -eq $var
else
echo Nothing is equal

fi
note

if [[ $var == 10 ]] Space is needed after the open square bracket and before the closing square bracket

for loop in bash script

Basic for loop

Basic for loop in bash script

for (( expression; condition; expression))
do
command
done

The code below reads words at the command prompt into the names array then loops through the array and prints the data from the array.

#!/bin/bash

# -a for array in read
echo "Enter array names"
read -a names
echo "Names : ${names[0]}, ${names[1]}"
echo "The length : ${#names[@]}"
for (( i=0; i<${#names[@]}; i++ ))
do
echo -n -e "${names[i]}\t"
done

for loop one-liner in bash

for i in `seq 1 3`; do echo "Hello ${i}"; done
output
Hello 1
Hello 2
Hello 3

for loop - network scan one-liner

Scan the network between the ip range ending with 192.168.84.100-200 with nc

for i in {100..200}; do nc -v -n -z -w 1 192.168.84.$i 443; done