Skip to main content

Shell Scripting

Basic Commands

echo $0

display current shell

cat /etc/shells

display available shells

cat /etc/passwd

shows user's shell e.g. /bin/bash)

chmod a+x scriptname

allow execute permission for all

./script.bash

execute from current location

/home/userdir/script.bash

execute from absolute location

 

Script Components

#!/bin/bash

Shell

# This script does X

Comment

echo/cp/grep

Command

if/while/for

Statement

 

Basic Scripts

nano output-screen

#!/bin/bash

# made by Nicolas Sotelo

whoami

echo

pwd

echo

hostname

echo

ls -ltr

echo

shell

comment

command

space

 

Variables

nano variable-command

#!/bin/bash

a=Nicolas

b=Sotelo

c="Linux Class"

echo "My first name is $a"

echo "My surname is $b"

echo "My class is $c"


set variable


echo variable

 

Input / Output

#!/bin/bash
echo Hello, my name is Nicolas Sotelo

echo

echo What is your name?

read namevar

echo

echo Hello $namevar

echo





read sets variable to the user's input

echo variable

#!/bin/bash
hnvar=`hostname`
echo Hello, my hostname is $hnvar
echo

echo What is your name?

read namevar

echo

echo Hello $namevar

echo


set variable as a `command`
echo the output

 

If-then scripts

#!/bin/bash
count=100

if [ $count -eq 100 ]

then

echo Count is 100

else

echo Count is not 100

fi








end if statement

#!/bin/bash
 

clear

if [ -e /home/nsotelo/error.txt ]

 

then

echo "File exists"

else

echo "File does not exist"

fi

 

#!/bin/bash

 

clear

echo

echo "What is your name?"

echo

read namevar

echo

 

echo Hello $namevar sir

echo

 

echo "Do you like working in IT? (y/n)"

read Like

echo

 

if [ "$Like" == "y" ]

then

echo "You are cool"

 

elif [ "$Like" == "n" ]

then

echo "You should try IT, it's a good field"

echo

fi

 

 

For Loops

  • Runs repeatedly until specified number of variables is met

#!/bin/bash
for numv in 1 2 3 4 5

do

echo "Welcome $numv times"

done

 

assign 1 2 3 4 5 to numv

repeatedly display for each of the specified variables

#!/bin/bash

for actionv in eat run jump play

do

echo "See Nick $actionv"

done


assign eat run jump play to actionv

repeatedly display for each of the specified variables

#!/bin/bash

for filev in {1..5}

do

touch $filev

done

for loop to create 5 files named 1-5

#!/bin/bash

for filev in {1..5}

do

rm $filev

done

for loop to delete 5 files named 1-5

#!/bin/bash

i=1

for day in Mon Tue Wed Thu Fri

do

echo "Weekday $((i++)): $day"

done

specify days in for loop

#!/bin/bash

a=1

for username in `awk -F: '{print $1}' /etc/passwd`

do

echo "Username $((a++)) : $username"

done

list all users one by one from /etc/passwd file