linux lab
linux lab
1. Study of Unix/Linux general purpose utility command list (man, who, cat, cd, cp, ps, ls,
mv, rm, mkdir, rmdir, echo, more, date, time, kill, history, chmod, chown, finger, pwd, cal,
logout, shutdown etc.), vi editor, .bashrc, /etc/bashrc and environment variables.
2. Write a shell script program to: a) display list of user currently logged in; b) to copy
contents of one file to another.
3. Write a program using sed command to print duplicated lines of Input.
4. Write a grep/egrep script to find the number of words character, words and lines in a file.
5. Write an awk script to: a) develop a Fibonacci series; b) display the pattern of given string
or number.
6. Write a shell script program to a) display the process attributes; b) change priority of
processes; c) change the ownership of processes; d) to send back a process from foreground;
e) to retrieve a process from background ; f) create a Zombie process.
7. Write a program to create a child process and allow the parent to display “parent” and the
child to display “child” on the screen.
8. Write a makefile to compile a C program.
9. Study to execute programs using gdb to utilize its various features like breakpoints,
conditional breakpoints. Also write a shell script program to include verbose and xtrace
debug option for debugging.
10. Study to use ssh, telnet, putty, ftp, ncftp and other network tools.
Experiment 1
Aim: Study of Unix/Linux general purpose utility command list (man, who, cat, cd, cp, ps, ls,
mv, rm, mkdir, rmdir, echo, more, date, time, kill, history, chmod, chown, finger, pwd, cal,
logout, shutdown etc.), vi editor, .bashrc, /etc/bashrc and environment variables.
man: man command in Linux is used to display the user manual of any command that we can
run on the terminal.
who : The ‘who’ command displays all the users who have logged into the system currently.
$ who
Cat: used to create a file, to write something in the file and display the content of the file.
cat >test1.txt
This is test file #1.
cat test1.txt
Output: cat test1.txt test2.txt
cd : The ‘$ cd’ command stands for ‘change directory’ and it changes your current directory
to the ‘newfolder’ directory.
$ cd newfolder (assuming that there is a directory named 'newfolder' on your system)
cp : This ‘$ cp ‘ command stands for ‘copy’ and it simply copy/paste the file wherever you
want to.
cp file1.txt file2.txt
It will copy the content of file1.txt to file2.txt
ps: ps used to list the currently running processes and display information about those
processes.
$ps
ls : The ‘ls’ command simply displays the contents of a directory.
$ls
mv : The ‘$ mv’ command stands for ‘move’ and it simply move a file from a directory to
another directory.
$ mv /Documents/newfolder/file.txt ~/Documents
rm : The ‘$ rm ‘ command for remove and the ‘-r’ simply recursively deletes file.
$ rm file.txt
mkdir : The ‘$ mkdir’ stands for ‘make directory’ and it creates a new directory.
$ mkdir newfolder
rmdir : The ‘$ rmdir’ command deletes any empty directory we want to delete.
$ rmdir newfolder
echo: echo command in Linux is a built-in command that allows users to display lines of text
or strings that are passed as arguments.
echo "Geeks for Geeks"
more: As 'cat' command displays the file content. Same way 'more' command also displays
the content of a file. Only difference is that, in case of larger files, 'cat' command output will
scroll off your screen while 'more' command displays output one screenful at a time.
$more file1.txt
date: date command is used to display the system date and time.
$ date
time: The time command in Linux and Unix-like operating systems lets you determine how
long a specific command will take to run.
$ time ls
kill: kill command in Linux (located in /bin/kill), is a built-in command which is used to
terminate processes manually. kill command sends a signal to a process that terminates the
process.
kill [signal] PID
PID = The `kill` command requires the process ID (PID) of the process we want to terminate.
[signal] = We have to specify the signal and if we don’t specify the signal, the default signal
`TERM` is sent to terminate the process
history: history command is used to view the previously executed command.
$ history
chmod: The Linux chmod command is used to control file permissions, allowing you to
specify who can access files, search directories, and run scripts.
r: Read permissions. The file can be opened, and its content viewed.
w: Write permissions. The file can be edited, modified, and deleted.
x: Execute permissions. If the file is a script or a program, it can be run (executed).
To see the permission in a file
$ls -l new_ file.txt
To change the permission:
chmod u=rw,og=r new_file.txt
chown: The chown command allows you to change the user and/or group ownership of a
given file, directory, or symbolic link.
The following command will change the ownership of a file named file1 to a new owner
named linuxize:
chown linuxize file1
finger: Finger command is a user information lookup command which gives details of all the
users logged in. This tool is generally used by system administrators.
To install finger
$sudo apt-get install finger
To get the details.
$finger
pwd : The ‘$pwd’ command stands for ‘print working directory’ and as the name says,it
displays the directory in which we are currently
$pwd
cal: The cal command displays in its output the day, month, and day of the week on the
calendar in the command line terminal.
$ cal
logout command – Logout of a login shell. This command can be used by normal users to end
their own session.
shutdown: The shutdown command in Linux is used to shutdown the system in a safe way.
$ shutdown
vi Editor
The default editor that comes with the UNIX operating system is called vi (visual editor).
Using vi editor, we can edit an existing file or create a new file from scratch. we can also use
this editor to just read a text file.
To open vi editors, we just need to type the command mentioned below.
vi [file_name]
To enter in insert mode in vi editor in Linux we just need to press `i` on our keyboard and we
will be in insert mode. we can just start entering our content.
To exit vi or wim and commit your changes, press the Escape key to ensure you're in
Command mode, then type :wq and hit Enter.
.bashrc file: The .bashrc file is a script file that’s executed when a user logs in. The file itself
contains a series of configurations for the terminal session. This includes setting up or
enabling: coloring, completion, shell history, command aliases, and more.
It is a hidden file and simple ls command won’t show the file.
To view hidden files, you can run the below command:
$ ls -a
To view the bashrc file:
$ cat .bashrc
Environment Variables
Environment variables allow you to customize how the system works and the behavior of the
applications on the system.
To display the value of the HOME environment variable you would run:
$printenv HOME
It will show a list of all environment variables:
$printenv
Aim: Write a shell script program to: a) display list of user currently logged in; b) to copy
contents of one file to another.
The who command is a simple and effective way to display information about currently
logged-in users.
Syntax of who Command in Linux
who [options] [filename]
for example:
hduser@mahesh-Inspiron-3543:~$ who
hduser tty7 2018-03-18 19:08 (:0)
Aim: Write a program using sed command to print duplicated lines of Input.
Make a text file as an input file and write some lines in it.
$cat > geekfile.txt
1. Replacing all the occurrence of the pattern in a line : The substitute flag /g (global
replacement) specifies the sed command to replace all the occurrences of the string in the
line.
$sed 's/unix/linux/g' geekfile.txt
2. Replacing string on a specific line number : You can restrict the sed command to
replace the string on a specific line number. An example is
$sed '3 s/unix/linux/' geekfile.txt
3. Deleting lines from a particular file: To Delete a particular line say n in this example.
Syntax:
$ sed 'nd' filename.txt
Example:
$ sed '5d' filename.txt
8. Duplicating the replaced line with /p flag : The /p print flag prints the replaced line
twice on the terminal. If a line does not have the search pattern and is not replaced, then the
/p prints that line only once.
$sed 's/unix/linux/p' geekfile.txt
Experiment 4
Aim: Write a grep/egrep script to find the number of words character, words and lines in a
file.
Grep, an acronym for “Global Regular Expression Print”, is one of the most commonly used
commands in Linux. grep is a command-line utility that searches for a specific text string in
one or more files. It looks for the pattern in each line of the file and prints out the lines that
match it.
1. Case insensitive search
The -i option enables to search for a string case insensitively in the given file. It matches
the words like “UNIX”, “Unix”, “unix”.
grep -i "UNix" geekfile.txt
7. To print only the string and not the entire line, use the -o flag:
Awk is abbreviated from the names of the developers – Aho, Weinberger, and
Kernighan. Awk is a scripting language used for manipulating data and generating
reports. Awk is mostly used for pattern scanning and processing. It searches one or more
files to see if they contain lines that matches with the specified patterns and then perform
the associated actions.
seq 10| awk 'BEGIN {a=0; b=1} {print a; c=a+b; a=b; b=c}'
Output:
0
1
1
2
3
5
8
13
21
34
Consider the following text file as the input file for all cases below:
$cat > employee.txt
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000
Default behavior of Awk: By default Awk prints every line of data from the specified
file.
$ awk '{print}' employee.txt
Output:
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000
In the above example, no pattern is given. So the actions are applicable to all the lines.
Action print without any argument prints the whole line by default, so it prints all the lines
of the file without failure.
Print the lines which match the given pattern.
$ awk '/manager/ {print}' employee.txt
Output:
ajay manager account 45000
varun manager sales 50000
amit manager account 47000
Experiment 6
Aim: Write a shell script program to a) display the process attributes; b) change priority of
processes; c) change the ownership of processes; d) to send back a process from foreground;
e) to retrieve a process from background ; f) create a Zombie process
The ps command provides a snapshot of the current processes on your system. The basic
syntax is as follows:
ps [options]
To display process attributes in Linux, you can use various commands like ps, top, htop, and
pgrep. Here are some examples:
1. Using ps Command:
The ps command can display a wide range of process attributes. Here are a few
examples:
Display all processes:
ps aux
ps aux
Display specific process attributes (replace <PID> with the process ID):
ps -p <PID> -o pid,ppid,user,%cpu,%mem,cmd
ps -p <PID> -o pid,ppid,user,%cpu,%mem,cmd
2. Using top Command:
The top command displays real-time information about processes. By default, it sorts
processes by CPU usage, but you can change the sorting order and display other
attributes by pressing different keys while top is running.
Start top by simply typing:
top
top
htop
3. Using pgrep Command:
The pgrep command can be used to find processes based on various attributes like
process name, user, etc. It returns the process IDs of matching processes.
For example, to find the PID of a process named "apache2":
pgrep apache2
pgrep apache2
ps -p $(pgrep apache2) -o pid,ppid,user,%cpu,%mem,cmd
In Ubuntu (and other Linux distributions), you can change the priority of processes using the
nice and renice commands. These commands are used to adjust the scheduling priority of
processes, which affects their CPU time.
Using renice Command:
The renice command is used to change the priority of an already running process. It can be
used to increase or decrease the priority.
For example, to increase the priority of a process with PID 1234:
renice -10 1234
1. This will make the process with PID 1234 run with a higher priority(-10).
The priority range is typically from -20 (highest priority) to 20 (lowest priority).
Increasing priority for a process might result in other processes getting less CPU time.
chown: The chown command allows you to change the user and/or group ownership of a
given file, directory, or symbolic link.
The following command will change the ownership of a file named file1 to a new owner
named linuxize:
chown linuxize file1
If you have a command running, and need to put it into the background to free up your
terminal, you can press Ctrl + Z on your keyboard to stop the process.
$ sleep 10000
^Z
[1]+ Stopped sleep 10000
To see a list of jobs in the background, use the jobs command.
$ jobs -l
[1]+ 1650 Stopped sleep 10000
To bring a job back to the foreground, we can use the fg command.
$ fg
If we had multiple stopped jobs, we would need to use a percent sign and specify the job
ID to bring the appropriate one back to the foreground.
$ fg %1
If we want the command to continue executing while it’s in the background. we can use
the bg command, followed by an ampersand and the job ID. The following command will
make our stopped job resume, while keeping it in the background.
$ bg %1
[1]+ sleep 10000 &
Now we can see that the process is still in the background, but it shows a status of
“running” instead of “stopped.”
$ jobs -l
[1]+ 1650 Running sleep 10000 &
Zombie process:
When a child process dies, child process goes into zombie state if the parent process is not
aware of its death. For the parent, the child still exists but the child process is actually dead.
int main ()
{
pid_t p;
p = fork ();
if(p == 0){
printf(“I am child having PID %d\n”,getpid());
printf(“My parent PID is %d\n”,getppid());
}
else {
sleep(30);
printf(“I am a parent having PID %d\n”, getpid());
printf(“My child PID is %d”, p);
}
return 0;
}
Output:
In the output the child process is executed and terminated first. But when we execute
command “ps” the PID of child process is present as <defunct> which indicate a zombie
process because the parent process is executing in the background and it is unaware about the
termination of its child process.
Experiment 7
Aim: Write a program to create a child process and allow the parent to display “parent” and
the child to display “child” on the screen.
Algorithm:
Step 1: start
Step2: call the fork() function to create a child process fork function returns 2 values
step 3: which returns 0 to child process
step 4: which returns process id to the parent process
step 5:stop
Aim: Study to execute programs using gdb to utilize its various features like breakpoints,
conditional breakpoints. Also write a shell script program to include verbose and xtrace
debug option for debugging.
gdb is the acronym for GNU Debugger. This tool helps to debug the programs written in C,
C++, Ada, Fortran, etc. The console can be opened using the gdb command on terminal.
Start GDB
Go to your Linux command prompt and type “gdb”.
Gdb open prompt lets you know that it is ready for commands. To exit out of gdb,
type quit or q.
The program to be debugged should be compiled with -g option. The below given
C++ file that is saved as gfg.cpp. We are going to use this file.
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int findSquare(int a)
{
return a * a;
}
View breakpoints
In order to see the breakpoints, type “info b”.
Conditional breakpoints
It can be combined with if condition(if the condition fails, the breakpoint will not be set)
For example, break findSquare if a == 10.
Verbose mode
$ vi debug_quotes.sh
#!/bin/bash
echo "USER=$USER"
echo "Today's Date: $(date)
echo "SHELL=$SHELL"
save and close the file.
$ bash -n debug_quotes.sh
debug_quotes.sh: line 4: unexpected EOF while looking for matching `"'
debug_quotes.sh: line 5: syntax error: unexpected end of file
$
Output above shows that there is syntax error, double quotes ‘”‘ is missing. To fix this, put
double quotes at end of line which shows today’s date.
The -v option in bash command tells the shell script to run in verbose mode. In practice, this
means that shell will echo each command prior to execute the command. This is very useful
in that it can often help to find the errors.
Let’s us a shell script with the name “listusers.sh” with following content,
$ vi listusers.sh
#!/bin/bash
cut -d : -f1,5,7 /etc/passwd | grep -v sbin | grep sh | sort > /tmp/users.txt
awk -F':' ' { printf ( "%-12s %-40s\n", $1, $2 ) } ' /tmp/users.txt
#Clean up the temporary file.
/bin/rm -f /tmp/users.txt
Execute the script with -v option,
$ bash -v listusers.sh
Output:
In output above , script output gets mixed with commands of the scripts. But however , with -
v option , at least you get a better view of what the shell is doing as it runs your script.
Experiment 10
Aim: Study to use ssh, telnet, putty, ftp, ncftp and other network tools.
Telnet
Telnet is a network protocol that allows a user to communicate with a remote device. It is a
virtual terminal protocol used mostly by network administrators to remotely access and
manage devices. Administrator can access the device by telnetting to the IP address or
hostname of a remote device.
To use telnet, you must have a software (Telnet client) installed. On a remote device, a Telnet
server must be installed and running. Telnet uses the TCP port 23 by default.
One of the greatest disadvantages of this protocol is that all data, including usernames and
passwords, is sent in clear text, which is a potential security risk. This is the main reason why
Telnet is rarely used today and is being replaced by a much secure protocol called SSH.
SSH is a network protocol used to remotely access and manage a device. The key difference
between Telnet and SSH is that SSH uses encryption, which means that all data transmitted
over a network is secure from eavesdropping. SSH uses the public key encryption for such
purposes.
Like Telnet, a user accessing a remote device must have an SSH client installed. On a remote
device, an SSH server must be installed and running. SSH uses the TCP port 22 by default.
PuTTY: PuTTY is an open-source and completely free software that offers users the
possibility of transferring data securely. The client uses different file transfer protocols such
as SCP, SSH, SFTP, and Rlogin to encrypt the data and protect it from unauthorized use.
PuTTY allows users to connect to switches, routers, mainframes, and servers using SSH and
serial clients.
File transfer protocol (FTP) is an Internet tool provided by TCP/IP. The first feature of
FTP is developed by Abhay Bhushan in 1971. It helps to transfer files from one computer to
another by providing access to directories or folders on remote computers and allows
software, data, text file to be transferred between different kinds of computers. The end-
user in the connection is known as localhost and the server which provides data is known as
the remote host.
NcFTP
NcFTP is an FTP client program which debuted in 1991 as the first alternative FTP client. It
was created as an alternative to the standard UNIX ftp program, and offers a number of
additional features and greater ease of use. NcFTP is a command-line user interface program,
and runs on a large number of platforms.