Showing posts with label shell scripting. Show all posts
Showing posts with label shell scripting. Show all posts

Friday, June 11, 2010

Script make backup of all file names


#!/bin/bash
FILES="$@"
for f in $FILES
do
        # if .bak backup file exists, read next file
 if [ -f ${f}.bak ]
 then
  echo "Skiping $f file..."
  continue  # read next file and skip cp command
 fi
        # we are hear means no backup file exists, just use cp command to copy file
 /bin/cp $f $f.bak
done

How to add two floating point numbers ?

You can make you og 'bc' command to do the arithmatic operations in shell script.
Following script illustrates a sample implimentation

a 1.2
b 3.1
x=(echo $a +$b|bc)
echo $x

How would you get the character positions 10-20 from a text file?

cat filename.txt | cut -c 10-20


:)


If you have a string "one two three", Which shell command would you extract the strings?


Input="one two three"
for var in $Input
do
       i=0;
       var.$i=$var
       i=$i+1
done
echo $i
for ( i=0; i< $i; i++)
do
      echo `var.$i`
done


Its a little big solution but thats just a way of playing with script ;)



Tuesday, June 8, 2010

IF IN SHELL SCRIPT

$ cat > elf
#
#!/bin/sh
# Script to test if..elif...else
#
if [ $1 -gt 0 ]; then
  echo "$1 is positive"
elif [ $1 -lt 0 ]
then
  echo "$1 is negative"
elif [ $1 -eq 0 ]
then
  echo "$1 is zero"
else
  echo "Opps! $1 is not number, give number"
fi

Try above script as follows:
$ chmod 755 elf
$ ./elf 1
$ ./elf -2
$ ./elf 0
$ ./elf a
Here o/p for last sample run:
./elf: [: -gt: unary operator expected
./elf: [: -lt: unary operator expected
./elf: [: -eq: unary operator expected
Opps! a is not number, give number
Above program gives error for last run, here integer comparison is expected therefore error like "./elf: [: -gt: unary operator expected" occurs, but still our program notify this error to user by providing message "Opps! a is not number, give number".

SHELL COMPARISONS, CONDITIONS, CHECKS

For Mathematics, use following operator in Shell Script

Mathematical Operator in  Shell Script MeaningNormal Arithmetical/ Mathematical StatementsBut in Shell
   For test statement with if commandFor [ expr ] statement with if command
-eqis equal to5 == 6if test 5 -eq 6if [ 5 -eq 6 ]
-neis not equal to5 != 6if test 5 -ne 6if [ 5 -ne 6 ]
-ltis less than5 < 6if test 5 -lt 6if [ 5 -lt 6 ]
-leis less than or equal to5 <= 6if test 5 -le 6if [ 5 -le 6 ]
-gtis greater than5 > 6if test 5 -gt 6if [ 5 -gt 6 ]
-geis greater than or equal to5 >= 6if test 5 -ge 6if [ 5 -ge 6 ]

NOTE: == is equal, != is not equal.
For string Comparisons use
OperatorMeaning
string1 = string2string1 is equal to string2
string1 != string2string1 is NOT equal to string2
string1string1 is NOT NULL or not defined 
-n string1string1 is NOT NULL and does exist
-z string1string1 is NULL and does exist
Shell also test for file and directory types
TestMeaning
-s file   Non empty file
-f file   Is File exist or normal file and not a directory 
-d dir    Is Directory exist and not a file
-w file  Is writeable file
-r file   Is read-only file
-x file   Is file is executable
Logical Operators
Logical operators are used to combine two or more condition at a time
Operator           Meaning
! expressionLogical NOT
expression1  -a  expression2Logical AND
expression1  -o  expression2Logical OR

FEW LINUX COMMANDS RELATED TO PROCESS

For this purposeUse this CommandExamples*
To see currently running process ps$ ps
To stop any process by PID i.e. to kill processkill    {PID}$ kill  1012
To stop processes by name i.e. to kill processkillall   {Process-name}$ killall httpd
To get information about all running processps -ag$ ps -ag
To stop all process except your shellkill 0$ kill 0
For background processing (With &, use to put particular command and program in background)linux-command  &$ ls / -R | wc -l &
To display the owner of the processes along with the processes  ps aux$ ps aux
To see if a particular process is running or not. For this purpose you have to use ps command in combination with the grep command ps ax | grep  process-U-want-to see
For e.g. you want to see whether Apache web server process is running or not then give command$ ps ax | grep httpd
To see currently running processes and other information like memory and CPU usage with real time updates.top
See the output of top command.

$ top


Note 
that to exit from top command press q.
To display a tree of processespstree$ pstree

* To run some of this command you need to be root or equivalnt user.

HOW TO READ LINES OF DATA IN A SHELL SCRIPT?

There's a very easy way to solve this:
while read myline
do
  echo $myline
done < inputfile
If the fields in a given line are separated by a known delimiter, either a tab or a comma, for example, then I suggest that you could use the cut command to extract specific values.
To demonstrate, let's pull some useful data out of the /etc/passwd file, a file that has lines of data in known fields, separated with a ":" as the deilmiter. Here's a typical line of data-
unknown:*:99:99:Unknown User:/var/empty:/usr/bin/false

The first field (remember, they're separated by colons) is the account name, the second the encrypted password (not shown because it's in a separate 'shadow' file for security), then the remaining fields are account ID, group ID, full user name, home directory and login shell.
Let's just pull out login and full name to see what that looks like:
#!/bin/sh

while read inputline
do
  login=`(echo $inputline | cut -d: -f1)`
  fulln=`(echo $inputline | cut -d: -f5)`
  echo login = $login and fullname = $fulln
done < /etc/passwd

exit 0
You can see how the cut program makes this a straightforward task, albeit one that can be done more quickly in other scripting languages like Perl. But if you want to work with shell scripts, the combination of a while read loop with the input redirected and the great cutcommand should give you all the data parsing capabilities you need.

Shell Built in Variables

Shell Built in VariablesMeaning
$#Number of command line arguments. Useful to test no. of command line args in shell script.
$*All arguments to shell
$@Same as above
$-Option supplied to shell
$$PID of shell
$!PID of last started background process (started with &)
$? - (1) If return value is zero (0), command is successful.
(2) If return value is nonzero, command is not successful or some sort of error executing command/shell script.
This value is know as Exit Status.

Sunday, December 27, 2009

How would you get the character positions 10-20 from a text file?

How would you get the character positions 10-20 from a text file?

cut -c10-20

Or

substring ${string_variable_name:starting_position:length}

Or

cat filename.txt | cut -c 10-20

How to read arguments in shell program

How to read arguments in shell program

#!/bin/sh
for i in $*
do
echo $i
done

$# returns the number of parameters that are passed to a shell script
$? returns the exit code of the last executed command (0 : Successful, 1 or other: Failed)




On executig the above script with any number of command-line arguments it will display all the parameters.