Shell Script Which Gets Executed With Greetings – The Moment User Logs In

in Categories Time and Date last updated April 5, 2008

Write shell script which gets executed the moment user logs in, it should greet user

Script first finds out current hour using date command

Depend upon time of the day, it will say Good morning or Good afternoon to user.

Open your bash / shell startup file i.e. profile file – ~/.bash_profile and put path to this script in file as follow:
/home/you/path/to/script

Sample shell script to greet user

#!/bin/bash
# Shell program which gets executed the moment the user logs in, it should
# display the message "Good morning", "Good Afternoon", or "Good Evening"
# depnding upon the time which the user logs in.
# =====================================================================
# Q. How to run this script as soon as user logs in?
# A. Open your bash startup file aka profile file - ~/.bash_profile
# and put path to this script in file as follow:
# . /path/to/greetings.sh
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
# get current hour (24 clock format i.e. 0-23)
hour=$(date +"%H")
 
# if it is midnight to midafternoon will say G'morning
if [ $hour -ge 0 -a $hour -lt 12 ]
then
  greet="Good Morning, $USER"
# if it is midafternoon to evening ( before 6 pm) will say G'noon
elif [ $hour -ge 12 -a $hour -lt 18 ] 
then
  greet="Good Afternoon, $USER"
else # it is good evening till midnight
  greet="Good evening, $USER"
fi
 
# display greet
echo $greet

Menu Driven Shell Script

in Categories Decision Making last updated April 5, 2008

Explains how to write a menu driven Shell script, which has following options:
1. Contents of /etc/passwd
2. List of users currently logged
3. Present handling directory (working directory)
4. Exit

Take action as per selected option

#!/bin/bash
# A menu driven Shell script which has following options
# Contents of /etc/passwd
# List of users currently logged
# Prsent handling directory
# Exit
# As per option do the job
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
while :
do
 clear
 echo "   M A I N - M E N U"
 echo "1. Contents of /etc/passwd"
 echo "2. List of users currently logged"
 echo "3. Prsent handling directory"
 echo "4. Exit"
 echo -n "Please enter option [1 - 4]"
 read opt
 case $opt in
  1) echo "************ Conents of /etc/passwd *************";
     more /etc/passwd;;
  2) echo "*********** List of users currently logged";
     who | more;;
  3) echo "You are in $(pwd) directory";   
     echo "Press [enter] key to continue. . .";
     read enterKey;;
  4) echo "Bye $USER";
     exit 1;;
  *) echo "$opt is an invaild option. Please select option between 1-4 only";
     echo "Press [enter] key to continue. . .";
     read enterKey;;
esac
done

Shell Script to read any year and find whether it is a leap year or not

in Categories Time and Date last updated April 5, 2008

A leap year comes once every four years. It is the year when an extra day is added to the Gregorian calendar used by most of the world.

An ordinary year has 365 days. A leap year has 366 days. The extra day is added to the month of February. In an ordinary year, February has 28 days. In a leap year, it has 29 days. This extra day is called a leap day.

How do I find out leap year?

A year is a leap year if it can be evenly divided by four. For example, 1996 was a leap year. But a year is not a leap year if can be evenly divided by 100 and not by 400. This is why 1700, 1800, 1900 were not leap years, but 2000 was.

Shell script to determine if entered year is leap or not…

#!/bin/bash
# Shell program to read any year and find whether leap year or not
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
# store year
yy=0
isleap="false"
 
echo -n "Enter year (yyyy) : "
read yy
 
# find out if it is a leap year or not
 
if [ $((yy % 4)) -ne 0 ] ; then
   : #  not a leap year : means do nothing and use old value of isleap
elif [ $((yy % 400)) -eq 0 ] ; then
   # yes, it's a leap year
   isleap="true"
elif [ $((yy % 100)) -eq 0 ] ; then
   : # not a leap year do nothing and use old value of isleap
else
   # it is a leap year
   isleap="true"
fi
if [ "$isleap" == "true" ];
then
   echo "$yy is leap year"
else
   echo "$yy is NOT leap year"
fi

Shell script to read a character (upper or lower), digit, special symbol and display message according to the character entered

in Categories Decision Making last updated April 5, 2008

This script uses sed command to find out all digits or upper characters. -z string (conditional expression) will return true if the length of string is zero.

Script logic

Read one character
[1] Use sed command to determine input character is digit or not (sed -e ‘s/[A-Z]//g’))

[2] Attempt to match regex [0-9] i.e. all digit against the pattern space

[3] If successful, replace that portion matched with replacement // i.e. do nothing.
If digits are in input, it will replace all those digit, and if input is only digit, nothing is left i.e. string is zero and that is what tasted with -z conditional expression.

#!/bin/bash
# Shell script to read a character (upper or lower), digit, special symbol and
# display message according to the character entered
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
char=""
echo -n "Enter a one character : "
read char
# use sed command to determine input character is digit or not
# -e : start script
# s/[0-9]// : Attempt to match regex [0-9] i.e. all digit against the pattern space (echo $char).
# If  successful,  replace  that  portion  matched  with replacement i.e. // do nothing. 
# g : Global replacement
# so if digit are in input it will replace all those digit, and if input is only digit, nothing
# is left i.e. string is zero and that is what tasted with -z
if [ -z $(echo $char | sed -e 's/[0-9]//g') ]
then
	echo "$char is Number/digit"
elif [ -z $(echo $char | sed  -e 's/[A-Z]//g') ] # find out if character is upper
then
        echo "$char is UPPER character"
 
elif [ -z $(echo $char | sed -e 's/[a-z]//g') ] # find out if character is lower
then
        echo "$char is lower character"
else
	echo "$char is Special symbol" # else it is special character
fi

Shell Script to find the validity of a given date

in Categories Time and Date last updated April 5, 2008

Date is entered in mm/dd/yyyy format using a keyboard. Various conditions are applied to make sure date is valid. Read the program comments to get idea about program logic.

#!/bin/bash
# Shell program to find the validity of a given date
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
# store day, month and year
dd=0
mm=0
yy=0
 
# store number of days in a month
days=0
 
# get day, month and year
echo -n "Enter day (dd) : "
read dd
 
echo -n "Enter month (mm) : "
read mm
 
echo -n "Enter year (yyyy) : "
read yy
 
# if month is negative (<0) or greater than 12 
# then it is invalid month
if [ $mm -le 0 -o $mm -gt 12 ];
then
    echo "$mm is invalid month."
    exit 1
fi
 
# Find out number of days in given month
case $mm in 
    1) days=31;;
    2) days=28 ;;
    3) days=31 ;;
    4) days=30 ;;
    5) days=31 ;;
    6) days=30 ;;
    7) days=31 ;;
    8) days=31 ;;
    9) days=30 ;;
    10) days=31 ;;
    11) days=30 ;;
    12) days=31 ;;
    *) days=-1;;
esac
 
# find out if it is a leap year or not
 
if [ $mm -eq 2 ]; # if it is feb month then only check of leap year
then
	if [ $((yy % 4)) -ne 0 ] ; then
	   : #  not a leap year : means do nothing and use old value of days
	elif [ $((yy % 400)) -eq 0 ] ; then
	   # yes, it's a leap year
	   days=29
	elif [ $((yy % 100)) -eq 0 ] ; then
	   : # not a leap year do nothing and use old value of days
	else
	   # it is a leap year
	   days=29
	fi
fi
 
# if day is negative (<0) and if day is more than 
# that months days then day is invaild
if [ $dd -le 0 -o $dd -gt $days ];
then
    echo "$dd day is invalid"
    exit 3
fi
 
# if no error that means date dd/mm/yyyy is valid one
echo "$dd/$mm/$yy is a vaild date"

Shell Script to find out whether file has read, write and execute permission

in Categories File-management last updated April 5, 2008

There are three specific permissions on Unix-like (including Linux / Mac OS x) systems that apply to each user or class:
=> The read permission (r), which grants the ability to read a file. When set for a directory, this permission grants the ability to read the names of files in the directory
=> The write permission (w), which grants the ability to modify a file. When set for a directory, this permission grants the ability to modify entries in the directory. This includes creating files, deleting files, and renaming files.
=> The execute permission (x), which grants the ability to execute a file. This permission must be set for executable binaries in order to allow the operating system to run them. When set for a directory, this permission grants the ability to traverse its tree in order to access files or subdirectories, but not see files inside the directory (unless read is set).

SHELL CONDITIONAL EXPRESSIONS

You can use conditional expressions to find out file permissions. These are used by the [[ compound command and the test and [ builtin commands to test file attributes and perform string and arithmetic comparisons.

Conditional Expression Meaning
-a file True if file exists.
-b file True if file exists and is a block special file.
-c file True if file exists and is a character special file.
-d file True if file exists and is a directory.
-e file True if file exists.
-f file True if file exists and is a regular file.
-g file True if file exists and is set-group-id.
-h file True if file exists and is a symbolic link.
-k file True if file exists and its “sticky” bit is set.
-p file True if file exists and is a named pipe (FIFO).
-r file True if file exists and is readable.
-s file True if file exists and has a size greater than zero.
-t fd True if file descriptor fd is open and refers to a terminal.
-u file True if file exists and its set-user-id bit is set.
-w file True if file exists and is writable.
-x file True if file exists and is executable.
-O file True if file exists and is owned by the effective user id.
-G file True if file exists and is owned by the effective group id.
-L file True if file exists and is a symbolic link.
-S file True if file exists and is a socket.
-N file True if file exists and has been modified since it was last read.

Sample Shell Script

#!/bin/bash
# Shell script to find out whether file has read, write and execute 
# permission
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
echo -n "Enter file name : "
read file
 
# find out if file has write permission or not
[ -w $file ] && W="Write = yes" || W="Write = No"
 
# find out if file has excute permission or not
[ -x $file ] && X="Execute = yes" || X="Execute = No"
 
# find out if file has read permission or not
[ -r $file ] && R="Read = yes" || R="Read = No"
 
echo "$file permissions"
echo "$W"
echo "$R"
echo "$X"

Shell script to read a number and find whether the number is odd or even

in Categories Decision Making last updated April 5, 2008
#!/bin/bash
# Shell script to read a number and find whether the number is odd or even
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
echo -n "Enter numnber : "
read n
 
rem=$(( $n % 2 ))
 
if [ $rem -eq 0 ]
then
  echo "$n is even number"
else
  echo "$n is odd number"
fi

Shell Script to read source file and copy it to target file

in Categories Decision Making last updated April 5, 2008
#!/bin/bash
# Shell to read source file and copy it to target file. If the file
# is copied successfully then give message 'File copied successfully'
# else give message 'problem copying file'
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
echo -n "Enter soruce file name : "
read src
echo -n "Enter target file name : "
read targ
 
if [ ! -f $src ]
then
	echo "File $src does not exists"
	exit 1
elif [ -f $targ ]
then
	echo "File $targ exist, cannot overwrite"
	exit 2
fi
 
# copy file 
cp $src $targ
 
# store exit status of above cp command. It is use to 
# determine  if shell command operations is successful or not
status=$?
 
if [ $status -eq 0 ]
then
	echo 'File copied successfully'
else
	echo 'Problem copuing file'
fi

Shell script to read 5 digit number and calculate the sum of digit

in Categories Shell Math last updated April 4, 2008
#!/bin/bash
# Shell script to read 5 digit number and calculate the sum of digit
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
echo -n "Enter numnber : "
read n
 
# find out length of string using wc -c command
len=$(echo $n | wc -c)
 
# remove \n i.e. new line character
len=$(( $len - 1 ))
 
# use loop to go throug all digit one by one and calculate sum of digit on fly
for (( i=1; i <= $len; i++ ))
do
   sum=$(( $sum + $(echo $n | cut -c $i) ))
done
echo "Sum of $n is $sum"