Unix Practical Assignment
Unix Practical Assignment
Calendar:
If a user wants a quick view of the calendar in the Linux terminal, cal is the command for you. By default, the cal
command shows the current month calendar as output.
cal command is a calendar command in Linux which is used to see the calendar of a specific month or a whole
year.
Syntax:
cal [ [ month] year]
The rectangular bracket means it is optional, so if used without an option, it will display a calendar of the current
month and year.
cal : Shows current month calendar on the terminal with the current date highlighted.
cal -y : Shows the calendar of the complete current year with the current date highlighted.
cal 08 2000 : Shows calendar of selected month and year.
Display Current Date and Time
The syntax is:
date
date "+format"
date
Sample outputs:
Message Display
The echo command in Linux is a built-in command that allows users to display lines of text or strings that are
passed as arguments. It is commonly used in shell scripts and batch files to output status text to the screen or a file.
Syntax
echo [option] [string]
Here,
[options] = The various options available for modifying the behaviour of the `echo` command
[string] = It is the string that we want to display.
calc is another text-based calculator, similar to bc. It is a bit more friendly than bc and can do variable substitutions as
well. To find out more about using this program, at the Unix shell prompt, enter:
Assignment 2
All directories are separated by a slash (/). The /(root) directory is represented by the first slash (/), and the last
directory named is your current directory.
The full path name of the current working directory can be found in terminal by using the following command:
$pwd
Displaying the Current Working Directory Using Built-in pwd (pwd):
The ‘cd’ command allows users to change their current working directory within the file system. The
basic syntax of the `cd` command is as follows:
cd [directory]
Ex: $ cd document
mkdir - make a directory
You extend your home hierarchy by making sub-directories underneath it. This is done with the mkdir,
make directory, command. Again, you specify either the full or relative path of the directory:
Syntax
mkdir [options] directory
Common Options
-p create the intermediate (parent) directories, as needed
-m mode access permissions (SVR4). (We’ll look at modes later in this Chapter).
Examples
% mkdir /home/frank/data
or, if your present working directory is /home/frank the following would be equivalent:
% mkdir data
rmdir - remove directory
A directory needs to be empty before you can remove it. If it’s not, you need to remove the files first
Also, you can’t remove a directory if it is your present working directory; you must first change out
of it.
Syntax
rmdir directory
Examples
To remove the empty directory /home/frank/data while in /home/frank use:
% rmdir data
or
% rmdir /home/frank/data
ls - list directory contents
The command to list your directories and files is ls. With options it can provide information about the size,
type of file, permissions, dates of file creation, change and access.
Syntax
ls [options] [argument]
Common Options
When no argument is used, the listing will be of the current directory. There are many very useful options
for the ls command. A listing of many of them follows. When using the command, string the desired options
together preceded by "-".
-a lists all files, including those beginning with a dot (.).
-d lists only names of directories, not the files in the directory
-F indicates type of entry with a trailing symbol:
directories /
sockets =
symbolic links @
executables *
-g displays Unix group assigned to the file, requires the -l option (BSD only)
-or- on an SVR4 machine, e.g. Solaris, this option has the opposite effect
-L if the file is a symbolic link, lists the information for the file or directory the link references, not the
information for the link itself
-l long listing: lists the mode, link information, owner, size, last modification (time). If the file is a symbolic
link, an arrow (-->) precedes the pathname of the linked-to file.
The mode field is given by the -l option and consists of 10 characters. The first character is one of the
following:
To get a long listing:
% ls –al
Practical 3
Absolute and Relative Pathnames in UNIX
Absolute Path-name
An absolute path is defined as the specifying the location of a file or directory from the root directory(/).
To write an absolute path-name:
Start at the root directory ( / ) and work down.
Write a slash ( / ) after every directory name (last one is optional)
Ex
$cat abc.sql
will work only if the fie “abc.sql” exists in your current directory. However, if this file is not present in
your working directory and is present somewhere else say in /home/kt , then this command will work only
if you will use it like shown below:
cat /home/kt/abc.sql
Relative path
Relative path is defined as the path related to the present working directly(pwd). It starts at your current
directory and never starts with a / .
To be more specific let’s take a look on the below figure in which if we are looking for photos then
absolute path for it will be provided as /home/jono/photos but assuming that we are already present in jono
directory then the relative path for the same can be written as simple photos.
UNIX offers a shortcut in the relative pathname– that uses either the current or parent directory as
reference and specifies the path relative to it. A relative path-name uses one of these cryptic symbols:
.(a single dot) - this represents the current directory.
$pwd
/home/kt/abc
$cd .. ***moves one level up***
$pwd
/home/kt
..(two dots) - this represents the parent directory.
$pwd
/home/kt/abc ***moves two level up***
$cd ../..
$pwd
/home
Practical 4
The cat (concatenate) command is used to create, view, concatenate files in the Linux operating system. The touch
command is also used to create a file in a Linux system without content whereas the cat creates files with some
content. The cat command reads the content of a file and prompts it.
Syntax
The general syntax of the cat command is as follows:
$ cat [option]... FILE...
Ex
$ cat > file.txt
Copying Files
cp (copy)
cp file1 file2 is the command which makes a copy of file1 in the current working directory and calls it file2
What we are going to do now, is to take a file stored in an open access area of the file system, and use the cp
command to copy it to your unixstuff directory.
Moving files
mv (move)
mv file1 file2 moves (or renames) file1 to file2
To move a file from one place to another, use the mv command. This has the effect of moving rather than copying the
file, so you end up with only one file rather than two.
It can also be used to rename a file, by moving the file to the same directory, but giving it a different name.
We are now going to move the file science.bak to your backup directory.
First, change directories to your unixstuff directory (can you remember how?). Then, inside the unixstuff directory,
type
Removing files and directories
rm (remove), rmdir (remove directory)
To delete (remove) a file, use the rm command. As an example, we are going to create a copy of the science.txt file
then delete it.
Inside your unixstuff directory, type
% cp science.txt tempfile.txt % ls % rm tempfile.txt % ls
You can use the rmdir command to remove a directory (make sure it is empty first). Try to remove the backups
directory. You will not be able to since UNIX will not let you remove a non-empty directory.
Knowing File type -FILE Command
You need to use the file command to determine file type. File command tests each argument in an attempt to classify
it. There are three sets of tests, performed in this order: filesystem tests, magic number tests, and language tests. The
first test that succeeds causes the file type to be printed on screen.
Type the following command:
$ file /etc/passwd
Output
/etc/passwd: ASCII text
$ file /home/voffice/letter.doc
/home/voffice/letter.doc: Microsoft Office Document
Practical 6
WC command
wc stands for word count. As the name implies, it is mainly used for counting purpose.
It is used to find out number of lines, word count, byte and characters count in the files specified in the file
arguments.
wc [OPTION]... [FILE]...
Ex
cd [directory]
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
$ cat capital.txt
Hyderabad
Itanagar
Dispur
Patna
Raipur
$ wc state.txt
5 7 58 state.txt
OR
$ wc capital.txt
5 5 39 capital.txt
CMD Command (comparing)
cmp command in Linux/UNIX is used to compare the two files byte by byte and helps you to find out whether the
two files are identical or not.
When cmp is used for comparison between two files, it reports the location of the first mismatch to the screen if
difference is found and if no difference is found i.e the files compared are identical.
cmp displays no message and simply returns the prompt if the files compared are identical.
Syntax:
cmp [OPTION]... FILE1 FILE2
Ex:
$cmp file1.txt file2.txt
$cmp file1.txt file2.txt
file1.txt file2.txt differ: byte 9, line 2
/*indicating that the first mismatch found in
two files at byte 20 in second line*/
$cmp file1.txt file2.txt
$_
/*indicating that the files are identical*/
Finding common between two files
comm: This command is used to compare two sorted files.
Syntax: comm [options] file1 file2
One set of options allows selection of ‘columns’ to suppress.
-1: suppress lines unique to file1 (column 1)
-2: suppress lines unique to file2 (column 2)
-3: suppress lines common to file1 and file2 (column3)
Example: Only show column-3 that contains lines common between file1 and file2
$ comm -12 file1 file2
Practrical -7
File and Directory attributes listing
LS Command
ls lists files and directories. If the pathname is a file, ls displays information on the file according to the requested options. If
the pathname is a directory, ls displays information on the files and subdirectories therein. You may obtain information on a
directory itself using the -d option.
If you do not specify any options, ls displays only the file name(s). When ls sends output to a pipe or a file, it writes one name
per line; when it sends output to the terminal, it uses the -C (multi-column) format.
In the Linux operating system, there are two commands available to list the directory
contents.
ls (list) command
dir (directory) command
Syntax
The general syntax of the ls command is as follow −
$ ls [OPTION]... [FILE]...
To display the current directory content in the Linux/Unix system, we use the ls command as shown in
below.
$ ls
Here, we will display the list contents of a directory in long listing format as well as the author of each file,
date, and owner permission using -l option with the ls command in the Linux system.
vikash@home: ~ $ ls -l shadow
total 16
-rw-rw-r—1 vikash Vikash 34 Dec 26 19:28 file.txt
-rw-rw-r—1 vikash Vikash 34 Dec 26 19:28 file.txt
-rw-rw-r— 1 vikash Vikash 34 Dec 26 19:38 file.txt
drwxrwxr-x 2vikash vikash 4096 Dec 26 19:47 snow
File ownership
File ownership is an important component of Unix that provides a secure method for storing files. Every file
in Unix has the following attributes −
Owner permissions − The owner's permissions determine what actions the owner of the file can perform on
the file.
Group permissions − The group's permissions determine what actions a user, who is a member of the group
that a file belongs to, can perform on the file.
Other (world) permissions − The permissions for others indicate what action all other users can perform on
the file.
While using ls -l command, it displays various information related to file permission as follows −
$ls -l /home/amrood
-rwxr-xr-- 1 amrood users 1024 Nov 2 00:10 myfile
drwxr-xr--- 1 amrood users 1024 Nov 2 00:10 mydir
File Access Modes
The permissions of a file are the first line of defense in the security of a Unix system. The basic building
blocks of Unix permissions are the read, write, and execute permissions, which have been described below −
Read
Grants the capability to read, i.e., view the contents of the file.
Write
Grants the capability to modify, or remove the content of the file.
Execute
User with execute permissions can run a file as a program.
Changing Permissions
To change the file or the directory permissions, you use the chmod (change mode) command. There are two
ways to use chmod — the symbolic mode and the absolute mode.
Using chmod in Symbolic Mode
The easiest way for a beginner to modify file or directory permissions is to use the symbolic mode. With
symbolic permissions you can add, delete, or specify the permission set you want by using the operators in
the following table.
Sr.No. Chmod operator & Description
1 + Adds the designated permission(s) to a file or directory.
2 - Removes the designated permission(s) from a file or directory.
3 = Sets the designated permission(s).
EX
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
$chmod o+wx testfile
$ls -l testfile
-rwxrwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod u-x testfile
$ls -l testfile
-rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod g = rx testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Changing Owners and Groups
While creating an account on Unix, it assigns a owner ID and a group ID to each user. All the permissions
mentioned above are also assigned based on the Owner and the Groups.
Two commands are available to change the owner and the group of files −
chown − The chown command stands for "change owner" and is used to change the owner of a file.
chgrp − The chgrp command stands for "change group" and is used to change the group of a file.
Changing Ownership
The chown command changes the ownership of a file. The basic syntax is as follows −
$ chown user filelist
The value of the user can be either the name of a user on the system or the user id (uid) of a user on the
system.
The following example will help you understand the concept −
$ chown amrood testfile
$
Changes the owner of the given file to the user amrood.
Changing Group Ownership
The chgrp command changes the group ownership of a file. The basic syntax is as follows −
$ chgrp group filelist
The value of group can be the name of a group on the system or the group ID (GID) of a group on the
system.
Following example helps you understand the concept −
$ chgrp special testfile
$
Changes the group of the given file to special group.
Practical-8
How can we find out what shell we are using?
The following echo command or printf command should work:
echo "$SHELL"
OR
printf "My current shell - %s\n" "$SHELL"
Use the ps command with -p {pid} option. The following command selects the processes whose process ID
numbers appear in pid. Use the following command to find out which shell you are in:
ps -p $$
Sample outputs:
PID TTY TIME CMD
5217 ? 00:00:00 bash
More Commands
Use the following Linux or Unix commands:
chsh -s /bin/ksh – Change the shell used from /bin/bash (default) to /bin/ksh for your account using the chsh
command
Escaping , quoting
Escaping - providing a \ (backslash) before a wildcard to remove its special meaning
Quoting - enclosing the wildcard or entire pattern within quotes. Anything within these quotes is left alone
by the shell and not interpreted.
Escaping *
Escaping [ ]
Escaping the SPACE
Escaping the \
Escaping the newline character
EX: $rm 'chap*' or $rm chap\*
$rm "My Document.doc" or $rm My\ Document.doc
$echo 'The characters |, <, > and $ are special'
$echo The character \| , \< , \> and \$ are special
Note - Single quotes protect all the characters. Double quotes do not protect $ and ' (backquote)
Command substitution is an operation with dedicated syntax to both execute a command and to have this
command's output hold (stored) by a variable for later use.
thedate="$(date)"
We can then print the result using the command printf:
num="1"
name="Devil"
These kinds of variables are scalar variables as they could hold one value at a time.
1) Accessing variable
Variable data could be accessed by appending the variable name with ‘$’ as follows:
Ex shell script
#!/bin/bash
VAR_1="Shell"
VAR_2="Script"
echo "$VAR_1$VAR_2"
Output:
ShellScript
Practical-9
A program/command when executed, a special instance is provided by the system to the process.
A process can be run in two ways:
Method 1: Foreground Process : Every process when started runs in foreground by default, receives input
from the keyboard, and sends output to the screen. When issuing pwd command
$ ls pwd
Output:
$ /home/geeksforgeeks/root
Method 2: Background Process: It runs in the background without keyboard input and waits till keyboard
input is required. Thus, other processes can be done in parallel with the process running in the background
since they do not have to wait for the previous process to be completed.
Adding & along with the command starts it as a background process
$ pwd &
Since pwd does not want any input from the keyboard, it goes to the stop state until moved to the foreground
and given any data input. Thus, on pressing Enter:
Output:
[1] + Done pwd
$
Listing Running Processes
It is easy to see your own processes by running the ps (process status) command as follows −
$ps
PID TTY TIME CMD
18358 ttyp3 00:00:00 sh
18361 ttyp3 00:01:31 abiword
18789 ttyp3 00:00:00 ps
Show all the processes on the system
This will show not only your own processes, but all the other processes running under different users as
well. Combined with the -f option, this gives us a fairly useful output:
The file contains English words of numbers from 1 to 100. Thus, the file has 100 lines.
The head command will, by default, write the first ten lines of the input file to the standard output:
The file contains English words of numbers from 1 to 100. Thus, the file has 100 lines
$ head numbers_en.txt
one :1
two :2
three :3
four :4
five :5
six :6
seven :7
eight :8
nine :9
ten : 10
The tail Command
The syntax of using the tail command is quite straightforward, too:
The tail command will by default write the last ten lines of the input file to the standard output:
$ tail numbers_en.txt
ninety-one : 91
ninety-two : 92
ninety-three : 93
ninety-four : 94
ninety-five : 95
ninety-six : 96
ninety-seven : 97
ninety-eight : 98
ninety-nine : 99
one hundred : 100
Sort Command
SORT command is used to sort a file, arranging the records in a particular order.
How to Sort Lines in Text Files in Unix Using sort Command
Let’s start with a simple example. Consider a file named ‘file.txt’ with the following content:
$cat file.txt
$sort file.txt
GREP command in Unix
The grep command in Unix/Linux is a powerful tool used for searching and manipulating text patterns
within files.
Syntax of grep Command in Unix
The basic syntax of the `grep` command is as follows:
grep [options] pattern [files]
Consider the below file as an input.
$cat >greekfile.txt
unix is great os. unix was developed in Bell labs.
By default, grep displays the entire line which has the matched string. We can make the grep to display only the
matched string by using the -o option.
Give the command chmod +x 1.sh (to set execute bit so that you can execute)
if statement
This block will process if specified condition is true.
Syntax:
if [ expression ]
then
statement
fi
Implementing if statement
if [ expression1 ]
then
statement1
statement2
.
.
elif [ expression2 ]
then
statement3
statement4
.
.
else
statement5
fi
Switch statement
case statement works as a switch statement if specified value match with the pattern then it will execute a
block of that particular pattern
When a match is found all of the associated statements until the double semicolon (;;) is executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.
Syntax:
case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac
Implementing switch statement
CARS="bmw
#Pass the variable in string
case "$CARS" in
#case 1
"mercedes") echo "Headquarters - Affalterbach, Germany" ;;
#case 2
"audi") echo "Headquarters - Ingolstadt, Germany" ;;
#case 3
"bmw") echo "Headquarters - Chennai, Tamil Nadu, India" ;;
esac
Output
$bash -f main.sh
Headquarters - Chennai, Tamil Nadu, India.
Expression Evaluation
Command: expr
expr command can be used in UNIX to evaluate expressions.
Examples: [na1271052@nkcdgp-admin-n2 ~]$ expr 3 +2
Output : 5
[na1271052@nkcdgp-admin-n2 ~]$ expr 13 - 2
Output : 11 [na1271052@nkcdgp-admin-n2 ~]$ expr 13 / 2
Output : 6 (it is rounded to 6 instead of 6.5)
**Please mentioned the practical date as per your practical schedule which been displayed on
Colpoll**