Test your Shell Scripting Skills: – Program 15

scmuser created the topic: Test your Shell Scripting Skills: – Program 15

Devise a script that creates a lock file which prevents more than one user from running it. The lock file must be removed before script termination or if the user presses the interrrupt key.

Tagged :

Test your Shell Scripting Skills: – Program 16

scmuser created the topic: Test your Shell Scripting Skills: – Program 16

Assume that you have a number of files, downloaded from the internet, in the /home/kumar/download directory. The table of contents (TOC) is available in the file TOC_Download.txt in the form filename:description. The script should check each file in the download directory that does not have a description in the TOC file and prompt the user for the description. The TOC should be updated to maintain the list in sorted condition. The script must be immune to signals.

Tagged :

Test your Shell Scripting Skills: – Program 3

scmuser created the topic: Test your Shell Scripting Skills: – Program 3

Write a script that lists files by modification time when called with lm and by access time when called with la. By default, the script should show the listing of all files in the current directory.

renjith replied the topic: Re: Test your Shell Scripting Skills: – Program 3

#!/bin/ksh
if [ $# -gt 1 ]
then echo ” Usage list.sh [ml|la] { expected arguments lm or la or null } “;
fi

case $* in
lm) ls -lrt ;;
la) ls -lru ;;
“”) ls ;;
*) echo “Invalid argument ”
esac

Tagged :

List of Example Shell script can be found

rajeshkumar created the topic: List of Example Shell script can be found

www.it.uom.gr/teaching/linux/lsst/scripts/q7

Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

rajeshkumar replied the topic: Re: List of Example Shell script can be found
One more…

htaccess.wordpress.com/2007/12/08/unix-shell-script-examples/
Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

Tagged :

Shell script to read file line by line

rajeshkumar created the topic: Shell script to read file line by line

processLine(){
line="$@" # get all args
# just echo them, but you may need to customize it according to your need
# for example, F1 will store first field of $line, see readline2 script
# for more examples
# F1=$(echo $line | awk '{ print $1 }')
echo $line
}

### Main script stars here ###
# Store file name
FILE=""

# Make sure we get file name as command line argument
# Else read it from standard input device
if [ "$1" == "" ]; then
FILE="/dev/stdin"
else
FILE="$1"
# make sure file exist and readable
if [ ! -f $FILE ]; then
echo "$FILE : does not exists"
exit 1
elif [ ! -r $FILE ]; then
echo "$FILE: can not read"
exit 2
fi
fi
# read $FILE using the file descriptors

# Set loop separator to end of line
BAKIFS=$IFS
IFS=$(echo -en "\n\b")
exec 3<&0 exec 0<"$FILE" while read -r line do # use $line variable to process line in processLine() function processLine $line done exec 0<&3 # restore $IFS which was used to determine what the field separators are IFS=$BAKIFS exit 0

Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

Tagged :

Shell script to Print only Size and file name using unix command.

rajeshkumar created the topic: Shell script to Print only Size and file name using unix command.

Shell script to Print only Size and file name using unix command.

ls -l | tr -s " " " "| cut -d " " -f5,9

Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

puneetbhatia77 replied the topic: Re: Shell script to Print only Size and file name using unix command.

The command should be

ls -l | tr -s " " " "| cut -d " " -f5,8

Tagged :

Complete Linux & Shell Scripting Guide and Tutorial for Linux Admin and DevOps Engineer

linux-shell-scripting-guide-and-tutorial

Linux User Commands

Linux Admin Commands

Useful Tools in Linux

Linux Shell Scripting Collection and Interview Guide

Linux Troubleshooting Guide

Linux Quiz

Linux Exercise

Linux Bash Scripting Video Tutorial and CBT

Tagged : / / / / / / / / / / / / / / /

Shell Scripting (Bash) Training | Bash/Shell Scripting Course

shell-bash-scripting-training

Introduction

  • Introduction
  • Why Shell Scripting?
  • Linux Internal
  • What to Expect From This Course?
  • Prerequisites

Git fundamental

  • Introduction of git
  • Git setup
  • Basic operations in git
  • Github
  • Summary

A First Look At Shell Scripts

  • Introduction
  • Creating A Shell Script
  • Demo: A Note-Taking Script
  • Calling The Script
  • The Shebang
  • Naming Your Script
  • Demo: The type Command
  • Summary

Variables

  • Introduction
  • Demo: Variables
  • Using Variables in A Script
  • Using Variables: Good Habits
  • Reading Input
  • Debugging your Script
  • Summary

If, Then, Else

  • Introduction
  • Demo: The If Statement
  • The If Statement
  • Return codes
  • The Conditional Expression
  • Demo: The Conditional Expression
  • The Conditional Expression 2
  • Arithmetic Tests
  • Demo: Arithmetic Tests
  • The If Statement Revisited
  • And, Or, Not
  • Summary

Input and Output

  • Introduction
  • Output: echo and printf
  • Input: read revisited
  • Standard Streams and Redirection
  • Demo: Redirection
  • Summary

Control Flow

  • Introduction
  • While and Until
  • The Classic For Statement
  • The C-Style For Statement
  • Break and Continue
  • The Case Statement
  • && and ||
  • Summary

Variables 2

  • Introduction
  • Integer Variables
  • Arithmetic Expressions
  • Arithmetic Expressions 2
  • Read-only Variables
  • Exporting Variables
  • Arrays
  • Summary

Handling Script Parameters

  • Introduction
  • Special Variables
  • Shift
  • Getopts
  • Getopts: Handling Errors
  • Summary

Shell Functions

  • Introduction
  • Shell Functions
  • Shell Functions 2
  • Functions: Demo
  • Some Miscellaneous Remarks
  • Summary

Fun with Strings

  • Introduction
  • Removing Part Of A String
  • Search and Replace
  • Setting A Default Value
  • Conditional Expression Patterns
  • Regular Expressions in The Conditional Expression
  • End of Options
  • Summary

Many Ways to Run Your Script

  • Introduction
  • Running your Code
  • Nohup and The Background
  • Exec
  • At and Cron
  • Set and Shopt
  • Summary
Tagged : / / / / / / / / / / / / / / / / / / / / / / / / /

Understand Shell Script Parameters – Reference

shell-script-parameters

A parameter is an entity that stores values. It can be a name, a number or some special characters.

Bash shell provides two kind of parameters.

Positional Parameter and Special Parameter

Bash Positional Parameter – $0, $1, $2 ..

Positional parameters are the arguments given to your scripts when it is invoked. It could be from $1 to $N. When N consists of more than a single digit, it must be enclosed in a braces like ${N}.

The variable $0 is the basename of the program as it was called.

The following example gets two arguments and provides arithmetic operations result between those two integers.

First, create the arithmetic.sh shell script as shown below.

$ cat arithmetic.sh

#!/bin/bash

echo -e “\$1=$1”

echo -e “\$2=$2”


let add=$1+$2

let sub=$1-$2

let mul=$1*$2

let div=$1/$2

echo -e “Addition=$add\nSubtraction=$sub\nMultiplication=$mul\nDivision=$div\n”

Next, execute the arithmetic.sh with proper parameters as shown below.

$ ./arithmetic.sh 12 10

$1=12

$2=10

Addition=22

Subtraction=2

Multiplication=120

Division=1

In the above output $1 has the value 12, and $2 has 10.

Shell built-in ‘let’ allows arithmetic operation to be performed on shell variables. The above script does the arithmetic operations such as addition, subtraction, multiplication and division on the given parameters.

Set / Unset Bash Positional Parameters

The built in set command is used to set and unset the positional parameter.

First, create the positional.sh shell script as shown below.

$ cat positional.sh

#!/bin/bash

# From command line

echo -e “Basename=$0”

echo -e “\$1=$1”

echo -e “\$2=$2”

echo -e “\$3=$3”

# From Set builtin

set First Second Third

echo -e “\$1=$1”

echo -e “\$2=$2”

echo -e “\$3=$3”

# Store positional parameters with -(hyphen)

set – -f -s -t

echo -e “\$1=$1”

echo -e “\$2=$2”

echo -e “\$3=$3”

# Unset positional parameter

set —

echo -e “\$1=$1”

echo -e “\$2=$2”

echo -e “\$3=$3”

The above script prints the command line arguments first, then set command sets the positional parameter explicitly. Set with the – refers end of options, all following arguments are positional parameter even they can begin with ‘-’. Set with ‘–’ without any other arguments unset all the positional parameters.

Next, execute the positional.sh as shown below.

$ ./positional.sh

Basename=positional.sh

$1=12

$2=10

$3=

$1=First

$2=Second

$3=Third

$1=-f

$2=-s

$3=-t

$1=

$2=

$3=

Use Bash $* and $@ to Expand Positional Parameters

This example shows the value available in $* and $@.

First, create the expan.sh as shown below.

$ cat expan.sh

#!/bin/bash

export IFS=’-‘

cnt=1

# Printing the data available in $*

echo “Values of \”\$*\”:”

for arg in “$*”

do

echo “Arg #$cnt= $arg”

let “cnt+=1”

done

cnt=1

# Printing the data available in $@

echo “Values of \”\$@\”:”

for arg in “$@”

do

echo “Arg #$cnt= $arg”

let “cnt+=1”

done

Next, execute the expan.sh as shown below to see how $* and $@ works.

$ ./expan.sh “This is” 2 3

Values of “$*”:

Arg #1= This is-2-3

Values of “$@”:

Arg #1= This is

Arg #2= 2

Arg #3= 3

· The above script exported the value of IFS (Internal Field Separator) with the ‘-’.

· There are three parameter passed to the script expan.sh $1=”This is”,$2=”2″ and $3=”3″.

· When printing the each value of special parameter “$*”, it gives only one value which is the whole positional parameter delimited by IFS.

· Whereas “$@” gives you each parameter as a separate word.

Use $# to Count Positional Parameters

$# is the special parameter in bash which gives you the number of positional parameter in decimal.

First, create the arithmetic.sh as shown below.

$ cat arithmetic.sh

#!/bin/bash

if [ $# -lt 2 ]

then

echo “Usage: $0 arg1 arg2”

exit

fi

echo -e “\$1=$1”

echo -e “\$2=$2”

let add=$1+$2

let sub=$1-$2

let mul=$1*$2

let div=$1/$2

echo -e “Addition=$add\nSubtraction=$sub\nMultiplication=$mul\nDivision=$div\n”

If the number of positional parameters is less than 2, it will throw the usage information as shown below,

$ ./arithemetic.sh 10

Usage: ./arithemetic.sh arg1 arg2

Process related Parameters – $$ and $!

The special parameter $$ will give the process ID of the shell. $! gives you the process id of the most recently executed background process.

The following script prints the process id of the shell and last execute background process ID.

$ cat proc.sh

#!/bin/bash

echo -e “Process ID=$$”

sleep 1000 &

echo -e “Background Process ID=$!”

Now, execute the above script, and check the process id which its printing.

$ ./proc.sh

Process ID=9502

Background Process ID=9503

$ ps

PID TTY TIME CMD

5970 pts/1 00:00:00 bash

9503 pts/1 00:00:00 sleep

9504 pts/1 00:00:00 ps

$

Other Bash Special Parameters – $?, $-, $_

· $? Gives the exit status of the most recently executed command.

· $- Options set using set builtin command

· $_ Gives the last argument to the previous command. At the shell startup, it gives the absolute filename of the shell script being executed.

$ cat others.sh

#!/bin/bash

echo -e “$_”; ## Absolute name of the file which is being executed

/usr/local/bin/dbhome # execute the command.

#check the exit status of dbhome

if [ “$?” -ne “0” ]; then

echo “Sorry, Command execution failed !”

fi

echo -e “$-“; #Set options – hB

echo -e $_ # Last argument of the previous command.

In the above script, the last echo statement “echo -e $_” ($ underscore) also prints hB which is the value of last argument of the previous command. So $_ will give the value after expansion

$ ./others.sh

./others.sh

/home/oracle

Sorry, Command execution failed !

hB

hB

Tagged : / / / / / / / / / / / / / / / /

How to read XML file by using shell script ?

read-xml-file-using-shell-script

This was like the first time where I had to write something that will be able to read something out of a XML file using a shell script. Usually I would use Python/Perl as my favorite choices in such a scenario but in this one I really *had* to do all within a shell script.

This is an example of the type of XML file I had to read:

Fixed a new bug
Shoaib Mir
Sun, 02 May 2010
shoaibmir[@]gmail.com

I ended up having a shell script like this:

#!/bin/bash

#Looking for four keywords in here
for key in changelog name date email
do
OUTPT=`grep $key log.xml | tr -d '\t' | sed 's/^\([^<].*\)$/\1/' `
eval ${key}=`echo -ne \""${OUTPT}"\"`
done

# Getting the results in four specific arrays
changelogarr=( `echo ${changelog}` )
namearr=( `echo ${name}` )
datearr=( `echo ${date}` )
emailarr=( `echo ${email}` )

#Print all Arrays
echo ${changelogarr[@]}
echo ${namearr[@]}
echo ${datearr[@]}
echo ${emailarr[@]}

Which gives me an output:

shoaib@shoaib-desktop:~/Desktop$ ./readxml.sh
Fixed a new bug Shoaib Mir
Sun, 02 May 2010
shoaibmir[@]gmail.com

 

Reference:

Reading XML file using shell script

 

Tagged : / / / / / / / / / / / / / / /