Write Script, using case statement to perform basic math operation as

rajeshkumar created the topic: Write Script, using case statement to perform basic math operation as

Write Script, using case statement to perform basic math operation as
follows
+ addition
– subtraction
x multiplication
/ division
The name of script must be ‘q4’ which works as follows
$ ./q4 20 / 3, Also check for sufficient command line arguments

#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite
#
# Latest version can be found at http://www.nixcraft.com/
#
# Q4
#

if test $# = 3
then
case $2 in
+) let z=$1+$3;;
-) let z=$1-$3;;
/) let z=$1/$3;;
x|X) let z=$1*$3;;
*) echo Warning - $2 invalied operator, only +,-,x,/ operator allowed
exit;;
esac
echo Answer is $z
else
echo "Usage - $0 value1 operator value2"
echo " Where, value1 and value2 are numeric values"
echo " operator can be +,-,/,x (For Multiplication)"
fi

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

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

Tagged :

Write Script to see current date, time, username, and current directory

rajeshkumar created the topic: Write Script to see current date, time, username, and current directory

Write Script to see current date, time, username, and current directory

#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite
#
# Latest version can be found at http://www.nixcraft.com/
#
# Q5
#
echo "Hello, $LOGNAME"
echo "Current date is `date`"
echo "User is `who i am`"
echo "Current direcotry `pwd`"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

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

Tagged :

Write Script to see current date, time, username, and current directory

scmjobs created the topic: Write Script to see current date, time, username, and current directory

Write Script to see current date, time, username, and current directory???

rajeshkumar replied the topic: Re: Write Script to see current date, time, username, and current directory

#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite
#
# Latest version can be found at http://www.nixcraft.com/
#
# Q5
#
echo "Hello, $LOGNAME"
echo "Current date is `date`"
echo "User is `who i am`"
echo "Current direcotry `pwd`"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

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

Tagged :

Write script to print given number in reverse order

rajeshkumar created the topic: Write script to print given number in reverse order

Write script to print given number in reverse order, for eg. If no is 123 it must print as 321.

#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
# Script to reverse given no
#
# Algo:
# 1) Input number n
# 2) Set rev=0, sd=0
# 3) Find single digit in sd as n % 10 it will give (left most digit)
# 4) Construct revrse no as rev * 10 + sd
# 5) Decrment n by 1
# 6) Is n is greater than zero, if yes goto step 3, otherwise next step
# 7) Print rev
#
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find reverse of given number"
echo " For eg. $0 123, I will print 321"
exit 1
fi

n=$1
rev=0
sd=0

while [ $n -gt 0 ]
do
sd=`expr $n % 10`
rev=`expr $rev \* 10 + $sd`
n=`expr $n / 10`
done
echo "Reverse number is $rev"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

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

Tagged :

Write script to print given numbers sum of all digit,

rajeshkumar created the topic: Write script to print given numbers sum of all digit,
Write script to print given numbers sum of all digit, For eg. If no is 123 it’s sum of all digit will be 1+2+3 = 6.

#!/bin/bash
#
#
# Algo:
# 1) Input number n
# 2) Set sum=0, sd=0
# 3) Find single digit in sd as n % 10 it will give (left most digit)
# 4) Construct sum no as sum=sum+sd
# 5) Decrment n by 1
# 6) Is n is greater than zero, if yes goto step 3, otherwise next step
# 7) Print sum
#
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find sum of all digit for given number"
echo " For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"
exit 1
fi

n=$1
sum=0
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
sum=`expr $sum + $sd`
n=`expr $n / 10`
done
echo "Sum of digit for numner is $sum"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

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

Tagged :

Write script to print given number in reverse order, for eg. If no is

scmjobs created the topic: Write script to print given number in reverse order, for eg. If no is
Write script to print given number in reverse order, for eg. If no is 123 it must print as 321.

kd09714 replied the topic: Re: Write script to print given number in reverse order, for eg. If no is
what script you are looking for. eg shell, perl etc. ?

scmjobs replied the topic: Re: Write script to print given number in reverse order, for eg. If no is
its in shell but i got sols

Tagged :

Frequently Used Shell Script

rajeshkumar created the topic: Frequently Used Shell Script
Shell scripts to convert file names to lower case and upper case
To convert to lower case:

#!/bin/sh
for i in *
do
j=`echo $i | tr '[A-Z]' '[a-z]'`
mv $i $j
done

To convert to upper case:

#!/bin/sh
for i in *
do
j=`echo $i | tr '[a-z]' '[A-Z]'`
mv $i $j
done

Searching for a String in Multiple Files

grep -r "modules" .
grep -lr "modules" .
grep -lr "mod.*" .
grep -r "drupal\|joomla\|wordpress" .
grep -lr "mod.*" ./log*

Filesystems using more than 90% capacity

df -hP | awk '{x=$5;sub ("%","",x)}x>90'
df -h | awk '{if(NF==1){x=$0;getline;if(int($4)>90)print x,$0}else if(int($5)>90) print}'
df -kh | awk '/\/export/ && int($5) >= 90'

Filesystems using more than 90% capacity remotly

ssh -q rajesh 'df -hP' | awk '{x=$5;sub ("%","",x)}x> 30'
ssh -q rajesh 'df -h' | awk '{if(NF==1){x=$0;getline;if(int($4)>60)print x,$0}else if(int($5)>60) print}'

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

Tagged :

Create a script haven’t been accessed for a week, then delete them

rajeshkumar created the topic: Create a script haven’t been accessed for a week, then delete them
Create a script for a cronjob that checks a special directory for files with the extension .tmp that haven’t been accessed for a week, then delete them. Also remove all empty directories.

#!/bin/bash

usage()
{
echo "Usage: $0 [-d Valid Directory] [-e Valid File extension] [-a Access time in a day]" 1>&2;
exit 1;
}

while getopts ":d:e:a:" o; do
case "${o}" in
d)
d=${OPTARG}
if [ ! -d "$d" ]; then
echo "Directory $d not found"
usage
fi
;;
e)
e=${OPTARG}
echo "Passed file extension is $e"
;;
a)
a=${OPTARG}
echo "Passed number of days for access is $a"
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))

# for Debug for output
echo "Directory is $d"
echo "File extension is $e"
echo "Accessed time is $a"

# Based on Inputs, this will find the specified file and delete it found accessed according to parameters
#find $d -iname "*$e" -atime -$a -type f -print0
#find /root/raj -iname "*.txt" -atime -1 -type f -print0

find $d -iname "*$e" -atime -$a -type f -print0 | xargs -0 rm -rf

# This can be used as well but xargs would be faster for large file sets.
# find $d -iname "*$e" -atime -$e -type f | exec rm {} \;

# To Remove the empty directory
find $d -type d -empty -exec rmdir {} \;

if [ -z "${d}" ] || [ -z "${e}" ] || [ -z "${a}" ]; then
usage
fi

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

Tagged :

Questions to test your linux shell Script

rajeshkumar created the topic: Questions to test your linux shell Script

www.scmgalaxy.com/index.php?option=com_k…34&id=427&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=426&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=425&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=424&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=423&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=422&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=419&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=421&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=420&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=418&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=431&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=430&Itemid=442
www.scmgalaxy.com/index.php?option=com_k…34&id=428&Itemid=442
Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

sribhavani_u replied the topic: Questions to test your linux shell Script
#assignment question1
#You have a number of C programs that certain comment lines at the beginning of each program. The lines begin with /* followed by the first line of comment, butthe terminator line has */ as the only characters in the line. Remove these comments from all files.
for file in *.c
do
echo “file name is $file”
if [ -e $file ]
then
`sed ‘s/[/**/]//g’ $file > newfile`
mv newfile $file
fi
done
=======================================================================
#assignment question1
#You have a number of C programs that certain comment lines at the beginning of each program. The lines begin with /* followed by the first line of comment, butthe terminator line has */ as the only characters in the line. Remove these comments from all files.
for file in test123.c
do
echo “file name is $file”
nooflines=`wc -l $file | awk ‘ { print $1 } ‘`
cat $file | grep -n “^/\*” | awk -F”:” ‘ { print $1 } ‘ | while read strtlineno
do
totlines=`wc -l $file | awk ‘ { print $1 } ‘`
let taillines=$nooflines-$strtlineno
endlineno=`tail -$taillines $file | grep -n “^\*/” | awk -F”:” ‘ { print $1 } ‘ | head -1`
let endlineno=$strtlineno+$endlineno
let difflines=$nooflines-$totlines
let strtlineno=$strtlineno-$difflines
let endlineno=$endlineno-$difflines
echo “$strtlineno $endlineno”
endlineno=`echo $endlineno\d`
sed -i $strtlineno,$endlineno $file
done
done
====================================================================
# assingment question2
#Write a script that compares two direcotries bar1 and bar2 (supplied as arguments) and copies or overwrites to bar1 from bar2 every file that is (i) not present in bar1 or (ii) newer than its namespace in bar1. (HINT: Use the find command)

BAR1=/root/test/bar1/
BAR2=/root/test/bar2/
BAR1_MOD=/root/test/bar1/

cd $BAR2

find . -type f | while read filename
do

newfile=false
modified=false
if [ ! -e “$BAR1$filename” ]; then
newfile=true
echo “ADD $filename”
elif ! cmp $filename $BAR1$filename &>/dev/null; then
modified=true
echo “MOD $filename”
fi

if $newfile || $modified; then

#massage the filepath to not include leading ./
filepath=$BAR1_MOD$(echo $filename | cut -c3-)

#create folder for it if it doesnt exist
destfolder=$(echo $filepath | sed -e ‘s/\/[^\/]*$/\//’)
mkdir -p $destfolder

#copy new/modified file to the upgrade folder
cp $filename $filepath
fi
done
====================================================================
#assingment question 3
#Add the statement #inlclude at the beginning of every C source file in the current directory containing printf or fprintf, if it does not already have it included.
egrep -l “printf|fprintf” *.c > new
for filename in `cat new`
do
if [ `grep -c “#include” $filename` -eq 0 ]; then
sed ‘1i\#include\’ $filename > new1
`cat new1>$filename`
rm new1
fi
done
rm new
====================================================================
#assingment question4
#!/bin/bash
#Find out the pathname of the Korn shell on your machine and then change the interpreter line in all shell script in the current directory that show a differentpathname for ksh
dest=`which ksh`
grep -l “^#!.*ksh” *.shh | while read filename
do
cat $filename | grep “^#!.*ksh” | while read src
do
sed -i “s|$src|$dest|g” $filename
done
done
=======================================================================
# assingment question 5
#!/bin/bash
#Write a script that displays a special listing showing the (i) permission (ii) size (iii) filename (iv) last modification time (v) last access time of filenames supplied as arguments. Provide suitable headers using the printf command.
if [ $# -eq 0 ]
then
echo “pass the file name”
exit
fi

divider==================================================
divider=$divider$divider$divider$divider

header=”\n %-15s %15s %15s %40s %40s\n”

format=” %-15s %15d %15s %40s %40s \n”

width=75

printf “$header” “PERMISSION” “SIZE” “FILENAME” “LASTMODTIME” “LASTACCESSTIME”

printf “%$width.${width}s\n” “$divider”

while [ $# -ne 0 ]
do
abc=`stat –format=%A” “%s” “%n” “\”%y\”” “\”%x\” $1 `
shift
printf “$format” \
$abc
done
======================================================================
# assingment question 6
#You are moving files to handled which accepts only 8+3 type filesname. Produce a list of those files in your current directory that fail in this test
#find . -type f ! -name “????????.???”
find . -type f -printf “%f\n” | while read filename
do
bname=`echo $filename | awk -F”.” ‘ { print $1}’ | wc -m`
ename=`echo $filename | awk -F”.” ‘ { print $2}’ | wc -m`
if [ $bname != 9 ] || [ $ename != 4 ]; then
echo “$filename”
fi
done
=======================================================================
#assingment question7
#Expand the scope of the script in 16.12 (Test Your Understanding) to perform search recursively.
======================================================================
#assingment question 8
#Display a process in the system every 30 seconds five times using a(i) while loop (ii) for loop. What is the unusual feature of the for loop?

#using while loop
#i=5
#while [ $i -gt 0 ]
#do
#echo “============”
#ps
#echo “===========”
#sleep 30
#i=$i-1
#done
#using for loop
for i in 1 2 3 4 5
do
echo “*******”
ps
echo “*******”
sleep 30
done

#for loop can not check for condition
=====================================================================
#assignment question 9
#Write a script that behaves both in interactive and noninteractive mode. When no arguments are supplied, it picks up each C program from the current directory and lists the first 10 lines. it then prompts for deletion of the file. if the user supplies arguments with the script, then it works on those files only.
args=$#

if [ $args -eq 0 ]
then
for i in $(find . -name “*.shh”)
do
echo “$(sed -n ‘1,10p’ $i)”
rm -i $i
done
else
for i in $*
do
if [ ! -f $i ]
then
echo “File $i does not exist”
else
echo “$(sed -n ‘1,10p’ $i)”
rm -i $i
fi
done
fi
=====================================================================
# assingment question 10
#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.

# Listing files by modification time and access time
s=$1
if test “$s” == “lm”
then
ls -lt
elif test “$s” == “la”
then
ls -lu
else
ls -l
fi
====================================================================
# assingment question 11
#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.
#!/bin/ksh
trap ” INT TERM QUIT
TOC=/root/test/download/contents.txt
find /root/test/download -type f | grep -v $TOC | awk -F/ ‘{ print $NF }’ | sort -u | while read fname
do
if [ `cat $TOC | grep -c “$fname”` == 1 ]; then
echo “file description exists for $fname”
else
echo “update description for $fname: ”
read desc > $TOC
sort -o /tmp/assing11.txt $TOC
cat /tmp/assing11.txt > $TOC
rm -f /tmp/assing11.txt
fi
done
===================================================================
#assingment question 12
#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.
setEnv()
{
LOCK=/tmp/mylock
}
checkLock()
{
if [ -f $LOCK ]; then
echo “Someone is running the script, Hence exiting…”
exit 1;
fi
}
createLock()
{
echo “Creating lock $LOCK”
touch $LOCK
}
doWork()
{
echo “Working”
sleep 10
}
removeLock()
{
echo “Removing lock $LOCK”
rm -f $LOCK
}
capkill()
{
removeLock
exit 1
}
########
# MAIN #
########
trap capkill INT TERM QUIT
setEnv
checkLock
createLock
doWork
removeLock
===================================================================
# assingment qestion 13
#Write a shell script that uses find to look for a file and echo a suitable message if the file is not found. you must not store the find output in a file.
echo “give the name of the file to be searched”
read file
if [ ` find . -type f -iname $file` ];
then
echo “$file exists”
else
echo “File \””$file”\” does not exist.”
fi

chaitu137 replied the topic: Questions to test your linux shell Script
Solution to Question 01

#!/bin/sh

sed -i ‘/\*/{D}’ *.c

Tagged :

Unable to delete script file /tmp/hudson

scmuser created the topic: Unable to delete script file /tmp/hudson
Hi,
I am getting build failure due to following issues….

FATAL: Unable to delete script file /tmp/hudson5099275030745290919.sh
hudson.util.IOException2: remote file operation failed: /tmp/hudson5099275030745290919.sh at hudson.remoting.Channel@3f08de20:mtv-ubld-39
at hudson.FilePath.act(FilePath.java:905)
at hudson.FilePath.act(FilePath.java:882)
at hudson.FilePath.delete(FilePath.java:1291)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:101)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:60)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:804)
at hudson.model.Build$BuildExecution.build(Build.java:199)
at hudson.model.Build$BuildExecution.doRun(Build.java:160)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:586)
at hudson.model.Run.execute(Run.java:1603)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
at hudson.model.ResourceController.execute(ResourceController.java:88)
at hudson.model.Executor.run(Executor.java:247)
Caused by: hudson.remoting.ChannelClosedException: channel is already closed
at hudson.remoting.Channel.send(Channel.java:516)
at hudson.remoting.Request.call(Request.java:129)
at hudson.remoting.Channel.call(Channel.java:714)
at hudson.FilePath.act(FilePath.java:898)
… 13 more
Caused by: java.io.IOException: Unexpected termination of the channel
at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:50)
Caused by: java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2596)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1316)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at hudson.remoting.Command.readFrom(Command.java:92)
at hudson.remoting.ClassicCommandTransport.read(ClassicCommandTransport.java:71)
at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:48)

Tagged :