Tuesday, January 29, 2013

Sample Shell Scripts

Sample Shell Scripts


Given an integer argument i, output the successive integers 1 to
2i to stdout.


#!/bin/bash
echo -n "Enter input i : "
read i
i=`expr 2 \* $i`
for j in `seq 1 $i`
do
  echo "$j"
done
The first line indicates the path for the bash shell.Bash is a unix shell
which stands for Bourne-again shell.It is a command processor which pro-
cesses scripts. The second and third line takes the input from the user,echo
is a command which displays the message to stdout by default and read command reads the input from the user. Now to output the successive integers 1 to 2i to stdout,a for loop with seq command is used.seq command prints sequence of numbers.
--------------------------------------------------------------------------------------------------------------------------------------
List all executable files in the current directory.

#!/bin/bash
echo ‘ls -l | grep -- -..x‘

The first line includes the path for the bash shell.To list all the executables
in the current directory,grep command is used. Initially ls -l lists all the files
in the current directory.The output of ls is given as input to grep command
using pipe. Grep command filters out the files with executables.
--------------------------------------------------------------------------------------------------------------------------------------
To modify the file name with the current date.

#!/bin/bash
d=‘date +%Y%m%d‘
str1=‘echo $1 | awk -F"." ’{print $1}’‘
str2=‘echo $1 | awk -F"." ’{print $2}’‘
name=$str1-$d.$str2
mv $1 $name

The first line includes the path for the bash shell.The second line gets
the current date in the format specified.And awk command is used to split
the filename and its extension.And then it is concatenated in the specified
format and replaced with the new file name.
--------------------------------------------------------------------------------------------------------------------------------------
To replace a word with another word in the file.

#!/bin/bash
touch $1;
string="horse is a animal,horse runs very fast"
echo $string > $1
sed -i ’s/horse/elephant/g’ $1
touch -t 201301011200.00 $1
  
The first line includes the path for the bash shell.The touch command
is used to create a new file.The file name is passed as command line argu-
ment.Then some data is added to the file.Sed command is used to replace the
horse word with the elephant word.The touch -t command is used to modify
the last modification time.


No comments:

Post a Comment