Linux Scripting - Paiet/Tech-Journal-for-Everything GitHub Wiki

Managing the Shell Environment

  • Login scripts:
    • /etc/profile
    • /etc/profile.d/*
    • ~/.profile
    • ~/.bash_profile
  • Bash configuration:
    • /etc/bashrc
    • ~/.bashrc
  • Logout script
    • ~/.bash_logout
  • Search path for executables defined:
    • Globally in /etc/profile
    • Per user in ~/.profile or ~/.bash_profile
  • When setting a variable, they are typically local to that specific shell instance.
    • Use export to convert them to global
      • export MESG
    • Add the following command to your .profile to make this automatic:
      • set -o allexport
  • Aliases
    • Add these to the .bashrc to automate commands
      • alias ls='ls --color=auto'
      • alias ls='ls --color=auto -la'
      • unalias ls
  • Functions
    • Add to .bashrc to create custom command sets
    • Can combine multiple commands in to a single command
    • Example system status function:

To Begin

function sysinfo()
	{
	echo -e "\nKernel Information:" ; uname -a
	echo -e "\nOS Version:" ; cat /etc/centos-release
	echo -e "\nSystem Uptime:" ; uptime
	echo -e "\nMemory Utilization:" ; free -m
	echo -e "\nFilesystem Utilization:"; df -h
	}

  • Update /etc/skel/.bashrc to populate values for new users

Writing Scripts

Example script

#!/bin/bash
MESG="This is my message"
echo $MESG

  • Set execute permissions chmod +x ./sample.sh

  • Add folder to PATH if you wish to call it without entering the directory

  • Basic Commands:

    • echo - Displays text on screen
    • echo -e - Displays text on screen and then awaits user input
    • read - Copies user input in to a variable
    • if/then/else - Performs a calculation and then acts on the results

Sample script to create a user account

#!/bin/bash
echo -e "Username:"
read username
if id -u $username > -1; then
	echo "That username already exists"
else
	echo -e "Full Name:"
	read fullname
	echo -e "Password:"
	read password
	useradd -c "$fullname" $username -p $password
	if id -u $username > -1; then
		echo "User created successfully"
	else
		echo "An error occurred while creating the user"
	fi
fi

  • More Commands:
    • for - Perform an action for each entry in a list
    • do - Execute an action
    • seq - Generate a list of numbers
    • while - Perform an action if certain conditions are met and loop
    • test - Perform a comparison and return true or false

Solution #1: Sample script to create ten files called video#.mp4

#!/bin/bash
for filenum in `seq 10`
do
    touch video$filenum.mp4
done

Solution #2: Sample script to create ten files called video#.mp4

#!/bin/bash
filenum=10
while [ $filenum -gt 0 ]
do
    touch video$filenum.mp4
    filenum=$(($filenum - 1))
done

Test if a user already has a home directory:

#!/bin/bash
echo -e "Username:"
read username
test -d /home/$username && echo "Home Directory Exists" || echo "Home Directory Does Not Exist"