You are on page 1of 16

UNIX and Shell Programming

ASSIGNMENT : 1

Explain the following commands :

 pwd :- pwd stands for Print Working Directory. It prints the path of the


working directory, starting from the root.

 who :- tells you who's logged on, and where they're coming from. Useful
if you're looking for someone who's actually physically in the same
building as you, or in some other particular location.

 ps -u yourusername  :- lists your processes. Contains lots of information


about them, including the process ID, which you need if you have to kill a
process.

 kill PID --- kills (ends) the processes with the ID you gave. This works
only for your own processes.

 Umask :- The umask (UNIX shorthand for "user file-creation mode


mask") is a four-digit octal number that UNIX uses to determine the file
permission for newly created files. Every process has its own umask,
inherited from its parent process.

 cd dirname  :- change directory. You basically 'go' to another directory,


and you will see the files in that directory when you do 'ls'. You always
start out in your 'home directory', and you can get back there by typing
'cd' without arguments. 'cd ..' will get you one level up from your current
position.

 mv filename1 filename2  :- moves a file (i.e. gives it a different name,


or moves it into a different directory.

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

 cp filename1 filename2  :- copies a file

 mkdir dirname  :- make a new directory

 rmdirdirname :- rmdir command removes empty directories specified


on the command line. These directories are removed from the filesystem
in the same order as they are specified on the command line, i.e., from
left to right. If the directory is not empty you get an error message.

 tr :- The tr command in UNIX is a command line utility for translating or


deleting characters. It supports a range of transformations including
uppercase to lowercase, squeezing repeating characters, deleting specific
characters and basic find and replace. 

 tee :- tee command reads the standard input and writes it to both the
standard output and one or more files.

 touch :- The touch command is a standard command used in


UNIX/Linux operating system which is used to create, change and
modify timestamps of a file.

 bc :- bc is an acronym for “basic calculator.” Use the bc command


in unix to run calculations through the command line terminal.

 exit :- The exit command terminates a script. It can also return a value,


which is available to the script's parent process.

 break :- break command is used to terminate the execution of for loop,


while loop and until loop. It can also take one parameter i.e.[N].

 more filename :- shows the first part of a file, just as much as will fit on
one screen. Just hit the space bar to see more or q to quit.

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

Explain the following commands with options :

 ls --- lists your files.

ls -a list all files including hidden file starting with '.'


ls –color colored list [=always/never/auto]
ls –d list directories - with ' */'
ls –F add one char of */=>@| to enteries
ls –i list file's inode index number
ls -l list with long format - show permissions
ls -la list long format including hidden files
ls -lh list long format with readable file size
ls -ls list with long format with file size
ls -r list in reverse order
ls -R list recursively directory tree
ls -s list file size
ls -S sort by file size
ls -t sort by time & date
ls –X sort by extension name

rm --- removes the entries.

recursive, which removes directories, removing the contents recursively


-r beforehand (so as not to leave files without a directory to reside in).

-i, interactive which asks for every deletion to be confirmed.


force, which ignores non-existent files and overrides any confirmation prompts
-f, (effectively canceling -i), although it will not remove files from a directory if the
directory is write-protected.

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

-v, verbose, which prints what rm is doing onto the terminal


directory, which deletes an empty directory, and only works if the specified
-d, directory is empty.

 sort ---rearranges the lines in a text file so that they are sorted,
numerically and alphabetically.

-b,
--ignore-leading- Ignore leading blanks.
blanks
-d, --dictionary-order Consider only blanks and alphanumeric characters.
-f, --ignore-case Fold lower case to upper case characters.
-g,
--general-numeric- Compare according to general numerical value.
sort
-i, --ignore-
Consider only printable characters.
nonprinting
-M, --month-sort Compare (unknown) < `JAN' < ... < `DEC'.
-h,
Compare human readable numbers (e.g., "2K", "1G").
--human-numeric-sort
-n, --numeric-sort Compare according to string numerical value.
-R, --random-sort Sort by random hash of keys.

 date ---used to print out, or change the value of, the system's time and
date information.

Display time described by string STRING, instead of the


-d, --date=STRING
default, which is 'now'.
Like --date, but processed once for each line of
-f, --file=DATEFILE
file DATEFILE.

-I[TIMESPEC], Output date/time in ISO 8601 format. For values


of TIMESPEC, use 'date' for date only (the default), 'hours',
--iso- 'minutes', 'seconds', or 'ns' for date and time to the indicated
8601[=TIMESPEC] precision.
-r, --reference=FILE Display the last modification time of file FILE.
-R, --rfc-2822 Output date and time in RFC 2822 format. Example: Mon,

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

07 Aug 2006 12:34:56 -0600


Output date and time in RFC 3339 format. TIMESPEC can
be set to 'date', 'seconds', or 'ns' for date and time to the
--rfc-3339=TIMESPEC indicated precision. Date and time components are
separated by a single space, for example: 2006-08-07
12:34:56-06:00
-s, --set=STRING Set time described by string STRING.
-u,--utc, --universal Print or set Coordinated Universal Time.

 cut ---removes ("cuts out") sections of each line of a file or files.

Select only the bytes from each line as specified


-b, --bytes=LIST in LIST. LIST specifies a byte, a set of bytes, or a range of
bytes; see Specifying LIST below.
Select only the characters from each line as specified
-c, --characters=LIST in LIST. LIST specifies a character, a set of characters, or a
range of characters; see Specifying LIST below.
-d, --delimiter=DELIM Use character DELIM instead of a tab for the field delimiter.
Select only these fields on each line; also print any line
containing no delimiter character, unless the -s option is
-f, --fields=LIST
specified. LIST specifies a field, a set of fields, or a range of
fields; see Specifying LIST below.
This option is ignored, but is included for compatibility
-n
reasons.
--complement Complement the set of selected bytes, characters or fields.
-s, --only-delimited Do not print lines not containing delimiters.

--output- Use STRING as the output delimiter string. The default is to


delimiter=STRING use the input delimiter.

 paste ---writes lines consisting of the sequentially corresponding lines from


each FILE, separated by tabs, to the standard output. With no FILE, or
when FILE is a dash ("-"), paste reads from standard input.

-d, --
Reuse characters from LIST instead of tabs.
delimiters=LIST
-s, --serial Paste one file at a time instead of in parallel.
--help Display a help message, and exit.
-c, --count Prefix lines with a number representing how many times they occurred.

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

-d, --repeated Only print duplicated lines.


Print all duplicate lines. delimit-method may be one of the following:
none
-D, Do not delimit duplicate lines at all. This is the default.
--all-repeated[=delimit- prepend Insert a blank line before each set of duplicated lines.
method]
separate Insert a blank line between each set of duplicated lines.
The -D option is the same as specifying --all-repeated=none.
Avoid comparing the first N fields of a line before determining
uniqueness. A field is a group of characters, delimited by whitespace.

This option is useful, for instance, if your document's lines are


-f N, --skip-fields=N numbered, and you want to compare everything in the line except the
line number. If the option -f 1 were specified, the adjacent lines
1 This is a line. 2 This is a line.
would be considered identical. If no -f option were specified, they would
be considered unique.
Normally, comparisons are case-sensitive. This option performs case-
-i, --ignore-case
insensitive comparisons instead.
Avoid comparing the first N characters of each line when determining
-s N, --skip-chars=N uniqueness. This is like the -f option, but it skips individual characters
rather than fields.
-u, --unique Only print unique lines.
-z, --zero-terminated End lines with 0 byte (null), instead of a newline.
-w, --check-chars=N Compare no more than N characters in lines.

 uniq ---filters out adjacent, matching lines from input file INPUT, writing
the filtered data to output file OUTPUT.

 gerp ---stands for "global regular expression print." It is a powerful tool for
matching a regular expression against text in a file, multiple files, or a
stream of input. It searches for the PATTERN of text you specified on the command
line, and outputs the results for you.

-e PATTERN, Use PATTERN as the pattern to match. This can specify multiple search
--regexp=PATTERN patterns, or to protect a pattern beginning with a dash (-).
-f FILE, --file=FILE Obtain patterns from FILE, one per line.
-i, --ignore-case Ignore case distinctions in both the PATTERN and the input files.
-v, --invert-match Invert the sense of matching, to select non-matching lines.

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

Select only those lines containing matches that form whole words. The
test is that the matching substring must either be at the beginning of the
line, or preceded by a non-word constituent character. Or, it must be
-w, --word-regexp
either at the end of the line or followed by a non-word constituent
character. Word-constituent characters are letters, digits, and
underscores.
-x, --line-regexp Select only matches that exactly match the whole line.
-y The same as -i.
 sed --- The sed stream editor performs basic text transformations on an input
stream.

-n, --quiet, --silent Suppress automatic printing of pattern space.


-e script,
Add the script script to the commands to be executed.
--expression=script
-f script-file,
Add the contents of script-file to the commands to be executed.
--file=script-file
--follow-symlinks Follow symlinks when processing in place.
-i[SUFFIX], Edit files in place (this makes a backup with file extension SUFFIX,
--in-place[=SUFFIX] if SUFFIX is supplied).
-l N, --line-length=N Specify the desired line-wrap length, N, for the "l" command.
--POSIX Disable all GNU extensions.
-r, --regexp-extended Use extended regular expressions in the script.
Consider files as separate rather than as a single continuous long
-s, --separate
stream.
Load minimal amounts of data from the input files and flush the
-u, --unbuffered
output buffers more often.
 awk --- The awk command runs AWK, a text-processing programming
language

-F fs Sets the input field separator to the regular expression fs.


-v var=value Assigns the value value to the variable var before executing the awk program.
'prog' An awk program.
-f progfile Specify a file, progfile, which contains the awk program to be executed.
file ... A file to be processed by the specified awk program.

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

Assignment 2
 Write a command to display “Hello friend, (current date in DD-MM-
YYYY) TODAY is (current date in DD-MM-YYYY) Good Day”

1. today=$(date +'%d/%m/%Y')
2. echo "Hello Friend, Today is ${today}. Good day!"

 Write a shell script to find smallest of three numbers that are read from
keyboard.

1. echo "Enter Number 1: "


2. read a
3. echo "Enter Number 2: "
4. read b
5. echo "Enter Number 3: "
6. read c
7. if [ $a -lt $b -a $a -lt $c ]
8. then
9. echo "${a} is the smallest number."
10. elif [ $b -lt $a -a $b -lt $c ]
11. then
12. echo "${b} is the smallest number."
13. else
14. echo "${c} is the smallest number."
15. fi
 Write a shell script which can be utilized as a calculator. Accept two
numbers and perform addition, subtraction, division and multiplication
operation.

1. echo "Enter Number 1: "


2. read a
3. echo "Enter Number 2: "
4. read b
5. echo "Select from given options"
6. echo "1 Addition"
7. echo "2. Subtraction"
8. echo "3. Multiplication"
9. echo "4. Divison"
10. echo "Enter your choice: "
11. read ch

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

12. case $ch in


13. 1) ans=`expr $a + $b`
14. echo "Addition is $ans.";;
15. 2) ans=`expr $a - $b`
16. echo "Subtraction is $ans.";;
17. 3) ans=`expr $a \* $b`
18. echo "Multiplication is $ans.";;
19. 4) ans=`expr $a / $b`
20. echo "Divison is $ans.";;
21. *) echo "Not a valid choice.";
22. esac

 Write a shell script to enter 10 records in a file.

1. for i in {1..10}
2. do
3. echo "Text ${i}" >> "file.txt"
4. done

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

 Write a shell script to count the total number of words and lines of the
given file.

1. echo "Enter a Filename:"


2. read fname
3. echo "Total number of words in $fname: `wc -w < $fname`"
4. echo "Total number of lines in $fname: `wc -l < $fname`"

 Write a shell script to check whether entered file exists or not.

1. echo "Enter Filename: "


2. read fname
3. if [ -e "$fname" ]
4. then
5. echo "$fname file exists."
6. else
7. echo "$fname file doesn't exist."
8. fi

 Write a shell script to check whether entered file readable or not.

1. echo "Enter Filename: "


2. read fname
3. if [ -r "$fname" ]
4. then
5. echo "$fname file is readable."
6. else
7. echo "$fname file is not readable."
8. fi

 Write a shell script to check whether the given file is empty or not.

1.echo "Ente
2. w=`wc --word < $fname`
3. if [ ${w} -eq 0 ];
4. then
5. echo "$fname is empty."
6. else
7. echo "$fname is not empty."
8. fi
9. r a Filename:"
10. read fname

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

 Write a shell script to reverse a number.

1. echo "Enter a number: "


2. read a
3. echo "Original Number is: $a"
4. b=0
5. while [ $a -gt 0 ]
6. do
7. b=$(expr $b \* 10)
8. k=$(expr $a % 10)
9. b=$(expr $b + $k)
10. a=$(expr $a / 10)
11. done
12. echo "Reversed Number is: $b"

 Write a shell script to reverse a string.

1. echo "Enter a String:"


2. read str
3. echo "Original String is: $str"
4. len=${#str}
5. for (( i=$len-1; i>=0; i-- ))
6. do
7. rev="$rev${str:$i:1}"
8. done
9. echo "Reversed String is: $rev"

 Write a shell script to check whether a given number is palindrome or


not.

1. echo "Enter the number"


2. read a
3. temp=$a
4. rev=0
5. while [ $a -gt 0 ]
6. do
7. b=`expr $a % 10 `
8. a=`expr $a / 10 `
9. rev=`expr $rev \* 10 + $b`
10. done
11. if [ $temp -eq $rev ]
12. then

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

13. echo "Number is a palindrome."


14. else
15. echo "Number is not a palindrome."
16. fi

 Write a shell script to create a command line calculator.


Example: $ mycal 20 + 10 Result: 30
$ mycal 20 / 10 Result: 2

1.mycal(){
2.re='^[0-9]+$'
3.if [ $# -ne 3 ]
4.then
echo "All parameters not inputed. Please provide a space
b/w parameters."
5. else
ans=`expr $1 $2 $3`
echo "Result: $ans"
6. fi
7.}
mycal 1 + 2

 Write a script to perform following operations using menu:


(a) Count alphabets
(b) Count numbers
(c) Count number of vowels

1. echo "Enter a String: "


2. read str
3. echo "----Menu----"
4. echo "1. Count Alphabets"
5. echo "2. Count Numbers"
6. echo "3. Count Vowels"
7. echo "Enter your choice:"
8. read no
9. case $no in
10. 1)alph=$( echo $str | grep -o -i "[a-z]" | wc -l)
11. echo "Total Alphabets: $alph";;
12. 2)num=$( echo $str | grep -o -i "[0-9]" | wc -l)
13. echo "Total Numbers: $num";;
14. 3)vowel=$( echo $str | grep -o -i "[a,e,i,o,u]" | wc -l)
15. echo "Total Vowels: $vowel";;
16. esac

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

 Write a shell script to accept n numbers and tell how many are positive,
negative and zero. Also display all numbers in ascending order.

1.echo -n "Enter the Total numbers :"


2. read n
3. echo "Enter numbers :"
4. i=0

5. while [ $i -lt $n ]
6. do
7. read a[$i]
8. i=`expr $i + 1`
9. done

10. for ((i = 0; i<$n; i++))


11. do
12. for((j = 0; j<$n-1; j++))
13. do
14. if [ ${a[j]} -gt ${a[$((j+1))]} ]
15. then
16. # swap
17. temp=${a[j]}
18. a[$j]=${a[$((j+1))]}
19. a[$((j+1))]=$temp
20. fi
21. done
22. done

23. arr=(0 0 0)
24. i=0
25. while [ $i -lt $n ]
26. do
27. if [ a[$i] -eq 0 ]
28. then
29. arr[0]=`expr ${arr[0]} + 1`
30. elif [ a[$i] -gt 0 ]
31. then
32. arr[1]=`expr ${arr[1]} + 1`
33. else
34. arr[2]=`expr ${arr[2]} + 1`
35. fi
36. i=`expr $i + 1`

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

37. done

38. echo "Output :"


39. echo "Positive numbers: ${arr[1]}"
40. echo "Zeroes: ${arr[0]}"
41. echo "Negative numbers: ${arr[2]}"
42. echo "Sorted Array: "
43. echo ${a[*]}

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

Assignment 3
Write command for following:

1. To display line numbers before each line.

 cat -n student.txt

2. To display line 10 to 15 from file f1.

 sed -n ’10,15 p ‘ f1

3. To remove all leading spaces from a file f1.

 sed ‘s/[ \t]*//’ f1

4. To display total number of words and lines of files for which filename
starts with 'm'.

 find . -name '/^[m]' | wc –w –l

5. To remove directory tree dir1/dir2/dir3 using single command.

 rmdir dir3/dir2/dir1

6. To remove all files that begins with digit from the parent directory to
current directory.

 Find . -name '/^[0-9]' -exec rm {} \;

7. To convert decimal 192 to hexadecimal.

 echo “obase=16; 192” | bc

8. To give read and write permission to file f1.

 chmodugo=rw f1

9. To give executable permission to file f2.

 chmodugo=x f2

Deep Vasava (T.Y.B.C.A) -54


UNIX and Shell Programming

10.Write a command to count number of characters in first five lines of file


x1.

 cat x1 | head -n ‘5’ | wc -c

11.Write a command using grep or sed or awk to display all lines that
contains 'ab*' in a line.

 grep “ab*” f1

12.Write a command using grep or sed or awk to display line 5 to 10 , 15 to


25 and last line of file f1.

 sed -n -e ‘5,10 p’ -e ’15,25 p’ -e ‘$ p’f1

13.Write a command using grep or sed or awk to locate lines that begins and
end with .(dot)

 sed -n "/^\./p"

14.Write a command using grep or sed or awk to replace all occurences of


'she' with 'he' and 'hi' with 'hello'.

 sed -e ‘s/she/he/’ -e ‘s/hi/hello/’ student

15.Write a command using grep or sed or awk to replace 'hello' with 'Good
Morning' in input file 'a1.sh' and write those lines to output file 'a2.sh'

 sed ‘s/hello/Good Morning/’ a1.sh > a2.sh

16.Write awk command to print odd number of word in each line.

 awk -F\ '{s="";for (i=1;i<=NF;i+=2) { {s=s?s FS


$i:$i} } print s}' Fname

Deep Vasava (T.Y.B.C.A) -54

You might also like