Monday, 2 September 2019

Shell Scripting Examples-1


Shell Script Examples
--------------------------------------------------------------------------------------------------------------------------
1). Hello World
#!/bin/sh
echo "Hello world"
--------------------------------------------------------------------------------------------------------------------------

2).Using Arguments
 Shell Script Arguments
#!/bin/bash
# example of using arguments to a script
echo "My first name is $1"
echo "My surname is $2"
echo "Total number of arguments is $#" 
--------------------------------------------------------------------------------------------------------------------------

3).#Write a script accept a user and check the given user exist or not?
echo -n "Enter a Username:"
read un
if grep -w $un /etc/passwd > /dev/null
then
echo "$un user exist"
else
echo "$un user doesn't exist"
fi
# /dev/null is a special file. It is used for to write unwanted output.
--------------------------------------------------------------------------------------------------------------------------

4).#Write a script accept a user and check the user is connect to the server or not?
echo -n "Enter user name"
read un
if grep -w $un /etc/passwd > /dev/null
then
if who | grep -w $un > /dev/null
then
    echo "Logged In"
 else
     echo "Not Logged In"
 fi 
else 
 echo "$un user doesn't exist",
fi
--------------------------------------------------------------------------------------------------------------------------

5).# Write a script accept a filename and open?
echo  -n "Enter a Filename:"
read fn
if[ -e $fn]
then
  if[-f $fn]
  then
    if[-r $fn] 
    then
     cat $fn
    else
    echo "No read permission"
    #chmod 644 $fn
    #cat $fn
    #echo "No read permission"
    fi
   else
    echo "It is not a file"
   fi
 else
  echo "$fn file doesn't exist"
fi
--------------------------------------------------------------------------------------------------------------------------
6).#Write a script accept a filename and check the file is regular file or directory file?
echo -n "Enter a filename:"
read fn
if [ -e $fn ]
then 
  if [ -f $fn]
  then
   echo "$fn is a regular file"
  elif [ -d $fn]
  then 
   echo "$fn is a directory file"
  else
 echo "It is not a file or directory" 
  fi
else 
  echo "fn file doesn't exist"
fi
--------------------------------------------------------------------------------------------------------------------------

7).#Write a script accept 2 filenames and chjeck the given 2 files are same or not?
echo -n "Enter a filename 1:"
read fn 1
echo -n "Enter a filename 2:"
read fn 2
x='cmp $fn1 $fn2'
if [ -z "$x" ]
then
echo "Given 2 files are same"
else
echo "Given 2 files are not same"
fi
--------------------------------------------------------------------------------------------------------------------------

8).#Write a script accept a string and check the given string is empty or not?
echo -n "Enter a string"
read str 
if [ -z "$str" ]
then
echo "Given string empty"
else
echo "Given string not empty"
fi
--------------------------------------------------------------------------------------------------------------------------

9).#Write a script accept a single character and check the given character is alphabet or digit or special character?
echo -n "Enter a single character:"
read ch
case $ch in
[a-zA-Z0-9])echo "Alphabet";;
[0-9]) echo "Digit";;
[^a-zA-Z0-9])echo "Special Character";;
*)echo "You entered more than one character";;
esac
--------------------------------------------------------------------------------------------------------------------------

10).#Write a script accept a single character and check the given character is special character or digit or vowel or consonent?
echo -n "Enter a single character:"
read ch 
case $ch in 
[^a-zA-Z0-9])echo "Special Character";;
[0-9]) echo "Digit";;
[AEIOUaeiou])echo "Vowel";;
[^AEIOUaeiou])echo "consonent";;
*)echo "You entered more than one character";;
esac
--------------------------------------------------------------------------------------------------------------------------












































































You can get a sizable sample text file by typing:


$ cp /home/msc/public/LinuxIntro/WaD.txt text_file.txt
Several versions of line counting across a set of files

This section develops several shell scripts, each counting the total number of lines across a set of files. These examples elaborate specific shell features. For counting the number of lines in one file we use wc -l. As a simple exercise you can replace this command with a call to the line counting script above.

Version 1: Explicit For loop

We use a for-loop to iterate over all files provided as arguments to the script. We can access all arguments through the variable $*. The sed command matches the line count, and replaces the entire line with just the line count, using the back reference to the first substring (\1). In the for-loop, the shell variable n is a counter for the number of files, and s is the total line count so far.

#!/bin/bash
# Counting the number of lines in a list of files
# for loop over arguments

if [ $# -lt 1 ]
then
  echo "Usage: $0 file ..."
  exit 1
fi

echo "$0 counts the lines of code" 
l=0
n=0
s=0
for f in $*
do
l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`
echo "$f: $l"
        n=$[ $n + 1 ]
        s=$[ $s + $l ]
done
echo "$n files in total, with $s lines in total"
--------------------------------------------------------------------------------------------------------------------------
Version 2: Using a Shell Function

In this version we define a function count_lines that counts the number of lines in the file provided as argument. Inside the function the value of the argument is retrieved by accessing the variable $1.


#!/bin/bash
# Counting the number of lines in a list of files
# function version

count_lines () {
  local f=$1  
  # this is the return value, i.e. non local
  l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`
}

if [ $# -lt 1 ]
then
  echo "Usage: $0 file ..."
  exit 1
fi

echo "$0 counts the lines of code" 
l=0
n=0
s=0
while [ "$*" != ""  ]
do
        count_lines $1
        echo "$1: $l"
        n=$[ $n + 1 ]
        s=$[ $s + $l ]
shift
done
echo "$n files in total, with $s lines in total"
-------------------------------------------------------------------------------------------------------------------------- Version 3: Using a return code in a function

This version tries to use the return value of the function to return the line count. However, this fails on files with more than 255 lines. The return value is intended to just provide a return code, e.g. 0 for success, 1 for failure, but not for returning proper values.


#!/bin/bash
# Counting the number of lines in a list of files
# function version using return code
# WRONG version: the return code is limited to 0-255
#  so this script will run, but print wrong values for
#  files with more than 255 lines

count_lines () {
  local f=$1  
  local m
  m=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`
  return $m
}

if [ $# -lt 1 ]
then
  echo "Usage: $0 file ..."
  exit 1
fi

echo "$0 counts the lines of code" 
l=0
n=0
s=0
while [ "$*" != ""  ]
do
        count_lines $1
l=$?
        echo "$1: $l"
        n=$[ $n + 1 ]
        s=$[ $s + $l ]
shift
done
--------------------------------------------------------------------------------------------------------------------------
echo "$n files in total, with $s lines in total"
-------------------------------------------------------------------------------------------------------------------------- Version 4: Generating the file list in a shell function

#!/bin/bash
# Counting the number of lines in a list of files
# function version
# function storing list of all files in variable files
get_files () {
  files="`ls *.[ch]`"
}

# function counting the number of lines in a file
count_lines () {
  local f=$1  # 1st argument is filename
  l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'` # number of lines
}

# the script should be called without arguments
if [ $# -ge 1 ]
then
  echo "Usage: $0 "
  exit 1
fi

# split by newline
IFS=$'\012'

echo "$0 counts the lines of code" 
# don't forget to initialise!
l=0
n=0
s=0
# call a function to get a list of files
get_files
# iterate over this list
for f in $files
do
        # call a function to count the lines
        count_lines $f
        echo "$f: $l"
# increase counter
        n=$[ $n + 1 ]
# increase sum of all lines
        s=$[ $s + $l ]
done

echo "$n files in total, with $s lines in total"
--------------------------------------------------------------------------------------------------------------------------
Version 5: Using an array to store all line counts

The example below uses shell arrays to store all filenames (file) and its number of lines (line). The elements in an array are referred to using the usual [ ] notation, e.g. file[1] refers to the first element in the array file. Note, that bash only supports 1-dimensional arrays with integers as indizes.

This section on arrays in the Advanced Bash-Scripting Guide:.


#!/bin/bash
# Counting the number of lines in a list of files
# function version

# function storing list of all files in variable files
get_files () {
  files="`ls *.[ch]`"
}

# function counting the number of lines in a file
count_lines () {
  f=$1  # 1st argument is filename
  l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'` # number of lines
}

# the script should be called without arguments
if [ $# -ge 1 ]
then
  echo "Usage: $0 "
  exit 1
fi

# split by newline
IFS=$'\012'

echo "$0 counts the lines of code" 
# don't forget to initialise!
l=0
n=0
s=0
# call a function to get a list of files
get_files
# iterate over this list
for f in $files
do
        # call a function to count the lines
        count_lines $f
        echo "$f: $l"loc
# store filename in an array
file[$n]=$f
# store number of lines in an array
lines[$n]=$l
# increase counter
        n=$[ $n + 1 ]
# increase sum of all lines
        s=$[ $s + $l ]
done
echo "$n files in total, with $s lines in total"
i=5
echo "The $i-th file was ${file[$i]} with ${lines[$i]} lines"
-------------------------------------------------------------------------------------------------------------------------- Version 6: Count only files we own

#!/bin/bash
# Counting the number of lines in a list of files
# for loop over arguments
# count only those files I am owner of

if [ $# -lt 1 ]
then
  echo "Usage: $0 file ..."
  exit 1
fi

echo "$0 counts the lines of code" 
l=0
n=0
s=0
for f in $*
do
  if [ -O $f ] # checks whether file owner is running the script
  then 
      l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`
      echo "$f: $l"
      n=$[ $n + 1 ]
      s=$[ $s + $l ]
  else
      continue
  fi
done

No comments:

Post a Comment

Streamlining the usage of GITHUB

Streamlining the usage of Github with Commands 1. Start a new git repository under one directory locally In this step, we need to bui...