Wednesday, September 23, 2009

SHELL SCRIPT

# How do you find out what’s your shell? - echo $SHELL
# What’s the command to find out today’s date? - date
# What’s the command to find out users on the system? - who
# How do you find out the current directory you’re in? - pwd
# How do you remove a file? - rm
# How do you remove a Directory ? rm -rf
# How do you find out your own username? - whoami
# How do you count words, lines and characters in a file? - wc
# How do you search for a string inside a given file? - grep string filename
# How do you search for a string inside a directory? - grep string *
# How do you search for a string in a directory with the subdirectories recursed? -grep -r string *
# How do you do Boolean logic operators in shell scripting? - ! tests for logical not, -a tests for logical and, and -o tests for logical or.
# How do you find out the number of arguments passed to the shell script? - $#
# What’s a way to do multilevel if-else’s in shell scripting? - if {condition} then {statement} elif {condition} {statement} fi
# How do you write a for loop in shell? - for {variable name} in {list} do {statement} done
# How do you write a while loop in shell? - while {condition} do {statement} done
# How does a case statement look in shell scripts? - case {variable} in {possible-value-1}) {statement};; {possible-value-2}) {statement};; esac
# How do you read keyboard input in shell scripts? - read {variable-name}
# How do you define a function in a shell script? - function-name() { #some code here return }

Check Whether a Directory is Empty or Not
#!/bin/bash
FILE=""
DIR=""
# init
# look for empty dir
if [ "$(ls -A $DIR)" ]; then
echo "$DIR is not Empty"
else
echo "$DIR is Empty"
fi
# rest of the logic
###############################################################
following find command will only print file name from /tmp. If there is no output, directory is empty.
$ find "/tmp" -type f -exec echo Found file {} \;
##################################################################

To search through a directory and find files containing text string mytest and then copy that file with that text string to another directory



#!/bin/bash
files="$(find /Test | xargs grep mytest | cut -d ":" -f1 | uniq)"
echo $files
for X in $files
do
cp $X /test1
done
####################################################################

Copy a file with password threw a shell script

read -p "Enter a password" pass
if test "$pass" == "nikhil"
then
cp -dpR /etc/resolv.conf /etc/resolv.conf.nikhil
echo "Password verified."
else
echo "Access denied."
fi
####################################################################

No comments: