0% found this document useful (0 votes)
7 views29 pages

UNIX Chapter 1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

What is Unix ?

The Unix operating system is a set of programs that act as a link between the computer and the
user. Unix is written using a C programming language.

The computer programs that allocate the system resources and coordinate all the details of the
computer's internals is called the operating system or the kernel.

➢ Architecture of UNIX Operating System

The UNIX operating system is divided into 4 prominent layers that


help define the interaction between the hardware and the user.
UNIX OS consists of a hardware layer, kernel layer, shell layer,
and applications layer. These layers together create a multiuser,
multitasking operating system.

• Layer-1: Hardware - This layer of UNIX consists of all


hardware-related information in the UNIX environment.
• Layer-2: Kernel- Kernel is a computer program that is
a core or heart of an operating system.
o It is the part of the OS that always resides in computer
memory and enables the communication between software and hardware components.

o It is the computer program that first loaded on start-up the system (After the bootloader). Once
it is loaded, it manages the remaining start-ups. It also manages memory, peripheral, and I/O
requests from software. Moreover, it translates all I/O requests into data processing
instructions for the CPU. It manages other tasks also such as memory management, task
management, and disk management.

➢ Functions of a Kernel

▪ Device Management:
A kernel manages the various peripheral devices connected to the computer and
controls them using device drivers.

▪ Memory Management:
A kernel controls the computer's memory and allocates it to processes safely. It
uses virtual addressing to prevent processes from crashing into each other.

▪ Resource Management:
A kernel shares resources between processes, ensuring that each process
uniformly accesses the resource. It also provides synchronization and inter-
process communication.

▪ Accessing Computer Resources:


A kernel is responsible for accessing computer resources such as RAM and I/O
devices.
➢ Types of Kernel :

1. Monolithic Kernel - In a monolithic kernel, all the operating system services run in kernel space,
which provides efficient communication between components. Example: Unix, Linux, Open VMS,
XTS-400 etc.
2. Micro Kernel – A microkernel only includes the essential services in kernel space, and other
services run in user space. This approach reduces the kernel's size and improves the system's
reliability. Example: Mach, L4, AmigaOS, Minix, K42 etc.

3. Hybrid Kernel – It is the combination of both monolithic kernel and microkernel. It has speed
and design of monolithic kernel and modularity and stability of microkernel. Example: Windows NT,
Netware, BeOS etc.
4. Exo Kernel - An exokernel is an operating system architecture that exposes the hardware
resources directly to user-level applications, Example: Nemesis, ExOS etc.

5. Nano Kernel – It is the type of kernel that offers hardware abstraction but without system
services. Micro Kernel also does not have system services therefore the Micro Kernel and Nano
Kernel have become analogous. Example: EROS etc.

Layer-3: The Shell– SHELL is a program which provides the interface between the user and an
operating system. When the user logs in OS starts a shell for user.
• The interface between the user and kernel. It is a program
that interprets/translates commands typed into the terminal into a series of commands that
can be sent to the shell. This script containing commands is called a shell script.
• There are various commands like cat, mv, cat, grep, id, wc, and many more.

➢ Types of Shell in UNIX System:


o Bourne Shell: This Shell is simply called the Shell. It was the first Shell for UNIX OS. It is still
the most widely available Shell on a UNIX system. It is faster and more preferred.

o C Shell: The C shell is another popular shell commonly available on a UNIX system. Bill Joy
created it at the University of California at Berkeley. It incorporated features such as aliases
and command history. It includes helpful programming features like built -in arithmetic and
C-like expression syntax.

o Korn Shell: It was written by David Korn at AT&T Bell Labs. It is a superset of the Bourne
shell. So it supports everything in the Bourne shell. It has interactive features. It includes
features like built-in arithmetic and C-like arrays, functions, and string-manipulation
facilities. It is faster than C shell.

Layer-4: Application Programs Layer - It is the outermost layer that executes the given external
applications.
➢ It executes external applications like word processors and graphic programs.
➢ UNIX distributions typically come with several useful applications programs as standard. For
Example: emacs editor, StarOffice, xv image viewer, g++ compiler etc.
➢ Difference between Shell and Kernel :
S.No. Shell Kernel

1. Shell allows the users to communicate with the kernel. Kernel controls all the tasks of the system.

2. It is the interface between kernel and user. It is the core of the operating system.

Its a low level program interfacing with the hardware


(CPU, RAM, disks) on top of which applications are
3. It is a command line interpreter (CLI). running.

Its types are – Monolithic Kernel, Micro kernel, Hybrid


4. Its types are – Bourne Shell, C shell, Korn Shell, etc. kernel, etc.

It carries out commands on a group of files by


5. specifying a pattern to match It performs memory management.

Shell commands like ls, mkdir and many more can be


used to request to complete the specific operation to
6. the OS. It performs process management.

7. It is the outer layer of OS. It is the inner layer of OS.

Kernel directly interacts with the hardware by


It interacts with user and interprets to machine accepting machine understandable language from the
8. understandable language. shell.

Provides services to other programs running on the


9. Interprets and translates user commands system

Operates at a lower level than the shell and interacts


Acts as an intermediary between the user and the with hardware
10. kernel

Enables user and applications to interact with


11. Executes commands and programs hardware resources

Features of UNIX Operating System:

• Open Source: Being open-source, the UNIX operating system is freely available to the
community for use and customization.
• Multitasking: The UNIX operating system allows you to launch several tasks or processes
from the same terminal, with one running in the foreground and the other in the background.
• Multi-user: Multiple users can access compute resources in a UNIX operating system.
Different terminals can be used to log in by the user. Time-sharing mechanisms are used
where a scheduler allots time to different jobs based on a scheduling technique.
• Utilities: Various types of tools are available on the UNIX operating system. These
include grep, sed, awk, etc. These tools can be used in compilers, network applications, and
remote services.
• Portability: Because a large percentage of the UNIX operating system is written in
the C language and only a tiny portion is coded for specific hardware, it ensures the transfer of
code to any computer system. This makes the UNIX operating system highly portable.
• File Security and Protection: UNIX is a multi-user which makes it more vulnerable to
security threats. Thus, UNIX places importance on file security and protection. UNIX security
measures include giving usernames and passwords, providing authentication, allowing file
access permissions, and file encryption .
• Command Structure: UNIX commands are straightforward to learn and use. Commands in
UNIX are case-sensitive (i.e. UNIX treats lowercase and uppercase characters separately) and
they are mostly written in lowercase. Example: cp, mv etc.
• Communication: UNIX operating system supports communication methods using
the write command, mail command, etc.
• Accounting: UNIX maintains track of the jobs that the user creates. This function improves
system performance by monitoring CPU use and verifying disk space. These accounting duties
may be performed by the root user using different commands such as quota, df, du, and so on.

Processes in Linux/Unix: A process refers to the active execution of a program.


➢ Types of Processes in Linux: There are various types of processes in Linux:

1. Parent and Child Process: A child process is a Linux process that is created by another process
known as the parent process. A child process can be created using one of two methods. The first
method is the fork system call, which is often used in Unix-like operating systems, whereas the
second method is the spawn method, which is preferred in the modern NT kernel of Microsoft
Windows. A process is considered a parent process if it creates one or more child (subprocess)
processes.

2. Zombie and Orphan process: A zombie process is a Linux process that has finished its execution
but still has an entry in the process table. Zombie processes usually get created when a child process
completes its execution but the parent process has yet to read its exit status.

An orphan process is a process that continues to run even after the parent process has been
completed or terminated. An orphan process can be intentionally or unintentionally created.

3. Daemon process: Daemon processes are system-related background processes. These


processes often run the permissions of root and service requests from other processes. Daemon
processes often run in the background, waiting for specified events or tasks to occur. Daemon
processes, unlike regular processes, do not require a controlling terminal to operate.
➢ Initializing a process: A process can be run in two ways:
• Foreground Processes: They run on the screen and need input from the user. For example,
Office Programs.

The process runs in the foreground, the output is directed to my screen, and if the ls command wants
any input (which it does not), it waits for it from the keyboard.

• Background Processes: They run in the background and usually do not need user input. For
example, Antivirus.

To start a background Linux process, add an ampersand (&) to the end of the command.

• Track Ongoing Process:

• In unix, We can use the ps command to display the list of the running processes.

$ ps
PID TTY TIME CMD
19 pts/1 00:00:00 sh
24 pts/1 00:00:00 ps

• The -f (f for full) option is one of the most commonly used options for the ps command, and it
offers extra information, as shown in the following example.

$ ps –f
UID PID PPID C STIME TTY TIME CMD
52471 19 1 0 07:20 pts/1 00:00:00f sh
52471 25 19 0 08:04 pts/1 00:00:00 ps -f

For a running program (named process) Pidof finds the process id’s (pids)
Fields described by ps are described as:
• UID: User ID that this process belongs to (the person running it)
• PID: Process ID
• PPID: Parent process ID (the ID of the process that started it)
• C: CPU utilization of process
• STIME: Process start time
• TTY: Terminal type associated with the process
• TIME: CPU time is taken by the process
• CMD: The command that started this process
There are other options which can be used along with ps command :
• -a: Shows information about all users
• -x: Shows information about processes without terminals
• -u: Shows additional information like -f option
• -e: Displays extended information
➢ Stopping a process:
When running in foreground, hitting Ctrl + c (interrupt character) will exit the command. For
processes running in background kill command can be used if it’s pid is known.
$ ps –f
UID PID PPID C STIME TTY TIME CMD
52471 19 1 0 07:20 pts/1 00:00:00 sh
52471 25 19 0 08:04 pts/1 00:00:00 ps –f
$ kill 19
Terminated
• If a process ignores a regular kill command, you can use kill -9 followed by the process ID.
$ kill -9 19
Terminated
Other process commands:
o bg: A job control command that resumes suspended jobs while keeping them running in the
background.
Syntax: bg [ job ]
For example: bg %19

o fg: It continues a stopped job by running it in the foreground.


Syntax: fg [ %job_id ]
For example, fg 19

o top: This command is used to show all the running processes within the working
environment of Linux.
Syntax: top
o nice: It starts a new process (job) and assigns it a priority (nice) value at the same
time. Syntax: nice [-nice value]
nice value ranges from -20 to 19, where -20 is of the highest priority.

o renice : To change the priority of an already running process renice is used. Syntax: renice [-
nice value] [process id]
o df: It shows the amount of available disk space being used by file systems. Syntax: df
Output:

Filesystem 1K-blocks Used Available Use% Mounted on

/dev/loop0 18761008 15246876 2554440 86% /

none 4 0 4 0% /sys/fs/cgroup

udev 493812 4 493808 1% /dev

tmpfs 100672 1364 99308 2% /run

none 5120 0 5120 0% /run/lock

none 503352 1764 501588 1% /run/shm

o free: It shows the total amount of free and used physical and swap memory in the
system, as well as the buffers used by the kernel. Syntax: free
Output:
total used free shared buffers cached
Mem: 1006708 935872 70836 0 148244 346656
-/+ buffers/cache: 440972 565736
Swap: 262140 130084 132056
FILES in UNIX:
• A file system is a logical collection of files on a partition or disk.
• A file is the smallest unit in which the information is stored.

➢ Types of Unix Files:


1. Ordinary Files: Ordinary files are the files in Unix, which includes program instructions, text, and
data.
o In ordinary files, there are no other files.
o Ordinary files are always placed under the directory file.
o Ordinary files are used to store our information like the text which we have to write or a
picture which we have to draw. This is the kind of the file which we mainly work with.
o In the long-format output of ls -l, the "-" symbol is used to specified such kind of file.

2. Directory: Directory store both special as well as ordinary files. A directory file includes an entry
file for each file and a subdirectory which it houses. If there are 5 files in a directory, then there will
be 5 entries in the directory. Every entry comprises of 2 components.
1. The name of the File.
2. An inode number, which is a unique identification number for the file or directory.

In the long-format output of ls -l, we used the "d" symbol in order to specify this kind of file.

3. Special Files: We use special files to represent the real physical device like terminal, tape drive,
and printer. and also used for Input/Output(I/O) operations. Special files or devices are used for
Input/Output(I/O) on Linux and Unix systems. They look as similar to the ordinary file or directory in a
file system.

This is one character at a time for the terminal devices.

o In the long-format output of ls -l, using the "c" symbol character distinct, files are marked.
o In the long-format output of ls -l, using the "b" symbol block, distinct files are marked.

4. Pipes: Pipes is like a temporary file that only exists to hold the data from one command till it is
read by another. A one-way flow of data is provided by the Unix pipe. In order to create a pipe, the
vertical bar (|) has to be placed on the command line between 2 commands. Such as who | wc -l.

In the long-format output of ls -l, known as pipes, are marked using the symbol "p."

5. Sockets: Unix sockets are a type of file that enables for advanced inter-process communication.
It is also known as inter-process communication socket. In the framework of the client-server
application, a Unix Socket is used.

In the long-format output of ls -l, using the "s" symbol, Unix sockets are marked.

6. Symbolic Link: The symbolic link is used to reference another file in the file system. In order to
reference another file of the file system, we use the symbolic link. The symbolic file will not function
if the source file is deleted or moved to the different location.

In the case of the long-format output of ls -l, using the "l" symbol, the symbolic link is marked.
Sr.No. Directory & Description
/
1 This is the root directory which should contain only the directories needed at the top
level of the file structure

2 /bin
This is where the executable files are located. These files are available to all users

3 /dev
These are device drivers
/etc
4 Supervisor directory commands, configuration files, disk configuration files, valid user
lists, groups, ethernet, hosts, where to send critical messages

5 /lib
Contains shared library files and sometimes other kernel-related files

6 /boot
Contains files for booting the system

7 /home
Contains the home directory for users and other accounts
/mnt
8 Used to mount other temporary file systems, such as cdrom and floppy for the CD-
ROM drive and floppy diskette drive, respectively
/proc
9 Contains all processes marked as a file by process number or other information that is
dynamic to the system

10 /tmp
Holds temporary files used between system boots
/usr
11 Used for miscellaneous purposes, and can be used by many users. Includes
administrative commands, shared files, library files, and others
/var
12 Typically contains variable-length files such as log and print files and any other type of
file that may contain a variable amount of data
/sbin
13 Contains binary (executable) files, usually for system administration. For
example, fdisk and ifconfig utlities

14 /kernel
Contains kernel files.

• /media:
The /media directory is used to mount removable media such as CDs, DVDs, and USB
drives.
• /opt:
The /opt directory is used to store additional software packages that are not part of the core
system.
• /run:
The /run directory contains temporary files that are created by system services and daemons.
The /srv directory is used to store data for services provided by the system.
• /sys:
The /sys directory is a virtual file system that provides information about the system's
hardware and devices.
Navigating the File System

1 cat filename
Displays a filename

2 cd dirname
Moves you to the identified directory

3 cp file1 file2
Copies one file/directory to the specified location

4 file filename
Identifies the file type (binary, text, etc)

5 find filename dir


Finds a file/directory

6 head filename
Shows the beginning of a file

7 less filename
Browses through a file from the end or the beginning

8 ls dirname
Shows the contents of the directory specified

9 mkdir dirname
Creates the specified directory

more filename
10
Browses through a file from the beginning to the end

mv file1 file2
11
Moves the location of, or renames a file/directory

pwd
12
Shows the current directory the user is in

rm filename
13
Removes a file

rmdir dirname
14
Removes a directory

tail filename
15
Shows the end of a file

touch filename
16
Creates a blank file or modifies an existing file or its attributes

whereis filename
17
Shows the location of a file

which filename
18 Shows the location of a file if it is in your PATH

]
System Calls in Operating System (OS):
• A system call is a way for a user program to interface with the operating system.
• The interface between a process and an operating system is provided by system calls.
➢ Types of System Calls:
➢ Process Control: Process control is the
system call that is used to direct the
processes. Some process control examples
include creating, load, abort, end, execute,
process, terminate the process, etc.

➢ File Management: File management is a


system call that is used to handle the files. Some
file management examples include creating files,
delete files, open, close, read, write, etc.

➢ Device Management: Device management is a


system call that is used to deal with devices. Some
examples of device management include read, device, write, get device attributes, release device, etc.

➢ Information Maintenance: Information maintenance is a system call that is used to maintain


information. There are some examples of information maintenance, including getting system data, set
time or date, get time or date, set system data, etc.

➢ Communication: Communication is a system call that is used for communication. There are some
examples of communication, including create, delete communication connections, send, receive
messages, etc.

➢ Some Methods Briefly:

o open()

The open() system call allows you to access a file on a file system. It allocates resources to the file and provides
a handle that the process may refer to. Many processes can open a file at once or by a single process only.

o read(): It is used to obtain data from a file on the file system. It accepts three arguments in general:
i.e. the file descriptor, buffer which stores read data and number of bytes to be read from
the file.

The file descriptor of the file to be read could be used to identify it and open it using open() before reading.
o wait()

In some systems, a process may have to wait for another process to complete its execution before proceeding.
When a parent process makes a child process, the parent process execution is suspended until the child
process is finished.

The wait() system call is used to suspend the parent process. Once the child process has completed its
execution, control is returned to the parent process.

o write():The write() system calls writes the data from a user buffer into a device such as a
file. This system call is one of the ways to output data from a program. In general, the
write system calls takes three arguments i.e. file descriptor, pointer to the buffer where
data is stored and number of bytes to write from the buffer.
o fork():
Processes generate clones of themselves using the fork() system call. It is one of the most common ways to
create processes in operating systems. When a parent process spawns a child process, execution of the parent
process is interrupted until the child process completes. Once the child process has completed its execution,
control is returned to the parent process.
o close()
It is used to end file system access. When this system call is invoked, it signifies that the program no longer
requires the file, and the buffers are flushed, the file information is altered, and the file resources are de-
allocated as a result.
o exec()
When an executable file replaces an earlier executable file in an already executing process, this system
function is invoked. As a new process is not built, the old process identification stays, but the new process
replaces data, stack, data, head, etc.
o exit()
The exit() is a system call that is used to end program execution. This call indicates that the thread execution
is complete, which is especially useful in multi-threaded environments. The operating system reclaims
resources spent by the process following the use of the exit() system function.

What Is POSIX?

POSIX stands for Portable Operating System Interface. It’s a family of standards specified by IEEE for
maintaining compatibility among operating systems. Therefore, any software that conforms to POSIX
standards should be compatible with other operating systems that adhere to the POSIX standards.

Here are some key aspects of POSIX as it pertains to Unix:

1. Standardized APIs: POSIX defines a set of standard APIs for various functionalities such as file I/O,
process control, interprocess communication, system calls, and more. By adhering to these APIs,
developers can write applications that are portable across POSIX-compliant operating systems.
2. Shell and Utilities: POSIX specifies a standard shell syntax and command-line utilities. This includes
commands like ls, cp, mv, rm, and others. It ensures that these commands have consistent behavior
across POSIX-compliant systems.
3. File System Structure: POSIX defines a standard file system structure, including directory hierarchy
and naming conventions. This helps maintain consistency in the organization of files and directories
across different Unix-like systems.
4. Process Control: POSIX specifies standards for process creation, termination, and control. This
includes fork/exec semantics, signals, and process groups.
5. Threads: POSIX defines a threading model that includes functions for creating, synchronizing, and
managing threads.
6. Interprocess Communication: POSIX provides standards for interprocess communication
mechanisms such as message queues, semaphores, and shared memory.
7. Environment Variables: POSIX specifies a set of standard environment variables that convey
information about the system and the user's environment.
8. Regular Expressions: POSIX defines a standard for regular expressions that is used in various
utilities and programming languages.
9. Networking: While the original POSIX standard focused more on single-user systems, subsequent
revisions, such as POSIX.1b and POSIX.1g, introduced features related to networking and real-time
systems.

Single user specification:

Single user operating system is also known as a single-tasking operating system, and a single-user
operating system is designed especially for home computers. A single user can access the computer at a
particular time. The single-user operating system allows permission to access your personal computer at
a time by a single user, but sometimes it can support multiple profiles.

Difference between Single User and Multi-User OS

Terms Single User Operating System Multi-User Operating System

Definition A Single-User Operating System is a A Multi-User Operating System is a system


system in which only one user can that allows more than one user to access a
access the computer system at a time. computer system at one time.
Bootloader The bootloader loads all the resources The bootloader distributes the resources of
of the CPU in the profile of a single the CPU based on the priority of the users.
superuser.

Super User A superuser gets all the powers of Superuser does not exist for a multi-user
maintaining the system and making operating system as each entity has control
changes to ensure the system runs over their working.
smoothly.

Complexity Single-User Operating System is The Multi-User Operating systems are


simple and easy to design. complicated as they have to apply complex
techniques to share the resources among
various users.

Performance Only one task at one time gets Schedules different tasks for performance at
performed. any rate.

Example MS-DOS, Windows 95, Windows NT, Mainframes, IBM AS400, Linux & Unix
Windows 2000, Personal Computers, Distributed OS, etc.
etc.

➢ Types of Single-user Operating Systems:

o Single-User Single-Tasking: Operating system allows a single user to execute one program at a
particular time. This operating system is designed especially for wireless phones and two -way
messaging. Some functions such as printing a document, and downloading images and videos are
performed in one given frame.
Example: MS-DOS, Palm OS (Used in Palm-held computers).
o Single-User Multi-Tasking: Operating system allows a single user to execute multiple programs
at the same time, the single user can perform multiple tasks at a time. This type of operating system
is found on personal desktops and laptops. This single-user multi-tasking can be pre-emptive or
cooperative.
• Pre-emptive: The operating system shares the central processing time by dedicating a single
slot to each of the programs.
• Co-operative: This is attained by relying on each process to give time to other methods in a
defined manner. Some example taking photos while capturing video, a user can perform different
tasks such as making calculations in excel sheets.
Example: Windows, Mac

Difference Between Distributed System and Parallel System:


➢ Functions of a Single User Operating System

1. Interpreting users commands: It takes the instructions from the user and passes them on to the
rest of the operating system. This is the part of the OS that the user interacts with to give instructions
to the computer. It can be command-driven, menu-driven or a GUI, which may use a WIMP system.

2. File management: It controls the organization of backing storage. It uses part of the disc as a file
catalogue, which holds details of where data is stored on the disc. Files are organized into a
hierarchical filing system storing files in separate directories and subdirectories.

3. Memory management: It controls where programs and data are placed in the main memory. Many OS's
allow more than one program to be in memory at the same time. Memory management ensures that
any program does not overwrite any other program (including the OS itself).

4. Input/output management: It communicates between the computer system and the input and output
devices. It handles the transfer of data between peripherals and the CPU.

5. Resource Allocation: The OS allocates resources to other programs such as applications. For example:

o Scheduler to share processor, e.g. batch, foreground or background, timesharing.

o Memory management - e.g. Virtual memory paging, swapping memory contents to hard disc.

o Ensures drivers are given access to hardware devices.

some common internal commands in Unix:

1. cd (Change Directory): Changes the current working directory.

cd [directory]

2. pwd (Print Working Directory): Displays the current working directory.


pwd
3. echo: Outputs text or variables to the console.

echo Hello, World!

4. alias: Creates an alias (shortcut) for a command.

alias ll= 'ls -l'

5. history: Displays a list of previously executed commands.


history
6. exit or logout: Exits the current shell or logs out the user.
exit
7. set: Displays or sets shell options and positional parameters.
set
8. unset: Removes the value of a variable or shell option.

unset VARIABLE
9. export: Sets the value of an environment variable.

export VARIABLE=value

10. source or dot: Executes commands from a file in the current shell session.

source filename

or
. filename

11. type: Displays information about a command, whether it's a shell built-in, an alias, or an external
command.
type command_name

12. jobs: Displays a list of background jobs.


jobs
13. bg: Puts a background job into the background.

bg %job_number

14. fg: Brings a background job to the foreground.

fg %job_number

15. kill: Sends a signal to terminate a process.

kill [signal] process_id

some common examples of external commands in Unix:

1. ls (List): Lists the files and directories in the current directory or a specified directory.
ls
2. cp (Copy): Copies files or directories.

cp source destination

3. mv (Move): Moves or renames files or directories.

mv source destination

4. rm (Remove): Removes files or directories.

rm file

5. cat (Concatenate): Displays the contents of a file or concatenates files.

cat filename

6. grep: Searches for a pattern in files.

grep pattern file

7. chmod (Change Mode): Changes file permissions.

chmod permissions file


8. chown (Change Owner): Changes the owner of a file or directory.

chown new_owner:new_group file

9. ps (Process Status): Displays information about running processes.

ps

10. kill: Sends a signal to terminate a process.

kill process_id

11. mkdir (Make Directory): Creates a new directory.

mkdir directory_name

12. rmdir (Remove Directory): Removes an empty directory.

rmdir directory_name

13. df (Disk Free): Displays information about disk space usage.


df
14. du (Disk Usage): Displays the disk usage of files and directories.
du
15. man (Manual): Displays the manual page for a command.

man command_name

uname command in Unix with Examples


In Unix-like operating systems, the uname command is used to display system information. The name
"uname" stands for "Unix Name." When you run the uname command in a terminal, it provides information
about the operating system and the machine on which it is executed.

1. -a option in uname

It prints all the system information in the following order: Kernel name, network node hostname, kernel
release date, kernel version, machine hardware name, hardware platform, operating system.
Syntax:
uname -a

2. -s option in uname
It prints the kernel name.
Syntax:
uname -s
3. -n option in uname
It prints the hostname of the network node(current computer).
Syntax:
uname -n

4. -r option in uname
It prints the kernel release date.
Syntax:
uname -r

5. -v option in uname
It prints the version of the current kernel.
Syntax:
uname -v

6. -m option in uname
It prints the machine hardware name.
Syntax:
uname -m

7. -p option in uname
It prints the type of the processor.
Syntax:
uname -p

8. -i option in uname
It prints the platform of the hardware.
Syntax:
uname -i

9. -o option in uname
It prints the name of the operating system.
Syntax :
uname -o
(tty):

In Unix-like operating systems, the file name associated with the terminal connected to the standard input
(tty) is typically /dev/tty. This special file represents the terminal device, and reading from or writing to
/dev/tty is a way to interact with the terminal.

For example, you can use the /dev/tty file in a script or command to prompt the user for input from the
terminal: Syntax of `tty` Command
tty [OPTION]....

#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name! You are interacting with $(tty)."

➢ Calculator (cal) command:


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]
• 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.
• cal 2018 : Shows the whole calendar of the year.

OPTIONS

Tag Description
-m Display monday as the first day of the week.
-j Display julian dates (days one-based, numbered from January 1).
-y Display a calendar for the current year.

➢ Display and Set Date and Time in unix


date command is used to display the system date and time. date command is also used to set date and time
of the system.

Syntax of Date Command:


date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
Examples

1. Display date with no options or default format

$ date
Wed Aug 5 15:02:59 IST 2020

2. Display universal date and time

$ date -u
Wed Aug 5 09:35:18 UTC 2020

3. Display a given string in date format. Note, this does not affect the systems' actual date and time value.

$ date --date=20200810
Mon Aug 10 00:00:00 IST 2020

4. To display current date and time.

$ date --date='now'
Wed Apr 14 13:51:45 IST 2021

5. To print the date of the day before yesterday:

$ date --date='2 days ago'


Mon Apr 12 13:50:15 IST 2021

6. To print the date next monday.

$ date --date='next monday'


Mon Apr 19 00:00:00 IST 2021

7. To display the date 84 days ago.

$ date --date='84 days ago'


Wed Jan 20 13:56:33 IST 2021

8. To display the date 2 months ago.

$ date --date='2 months ago'


Fri Jun 5 15:55:13 IST 2020

9. To print the date of the day three months and two days hence (from today).

$ date --date='3 months 2 day'


Fri Jul 16 14:00:59 IST 2021

10. Use --file option to show date mentioned on each line of the file in the DATEFILE. Let us have a DATEFILE
as datefile.txt

$ cat >> datefile.txt


next month
Sept 23, 2020
today
next monday
Ctrl+D

$ cat datefile.txt
next month
Sept 23, 2020
today
next monday

$ date --file=datefile.txt
Sat Sep 5 16:08:05 IST 2020
Wed Sep 23 00:00:00 IST 2020
Wed Aug 5 16:08:05 IST 2020
Mon Aug 10 00:00:00 IST 2020

11. To print the day (weekday) of Christmas in the current year:

$ date --date='25 Dec' +%a


Sat

12. To print the current weekday, full month name and the day of the month:

$ date '+%a, %B %d'


Wed, April 14

List of Format specifiers used with date command:


%D: Display date as mm/dd/yy. Examples:
%d: Display the day of the month (01 to 31). Command:
%a: Displays the abbreviated name for weekdays $date "+%D"
(Sun to Sat). Output:
%A: Displays full weekdays (Sunday to Saturday). 10/11/17
%h: Displays abbreviated month name (Jan to Dec). Command:
%b: Displays abbreviated month name (Jan to Dec). $date "+%D %T"
%B: Displays full month name(January to December). Output:
%m: Displays the month of year (01 to 12). 10/11/17 16:13:27
%y: Displays last two digits of the year(00 to 99). Command:
%Y: Display four-digit year. $date "+%Y-%m-%d"
Output:
%T: Display the time in 24 hour format as HH:MM:SS. 2017-10-11
%H: Display the hour. Command:
%M: Display the minute.
$date "+%Y/%m/%d"
Output:
%S: Display the seconds. 2017/10/11
Syntax: Command:
$date "+%A %B %d %T %y"
date +%[format-option] Output:
Thursday October 12 07:54:29 17
➢ Displaying Text/String:
The most straightforward usage of the echo command is to display a text or string on the terminal.
To do this, you simply provide the desired text or string as an argument to the echo command.
Syntax:
echo [string]
Example:
If we want to display “Geeks for Geeks”. We use the following command.
echo "Geeks for Geeks"
1. \b : it removes all the spaces in between the text
Example:
echo -e "Geeks \bfor \bGeeks"
2. \c : suppress trailing new line with backspace interpreter ‘-e‘ to continue without emitting new
line.
Example:
echo -e "Geeks \cfor Geeks"
3. \n : this option creates a new line from where it is used.
Example:
echo -e "Geeks \nfor \nGeeks"
4. \t : this option is used to create horizontal tab spaces.
Example: echo -e "Geeks \tfor \tGeeks"
5. \r : carriage return with backspace interpreter ‘-e‘ to have specified carriage return in output.
Example:
echo -e "Geeks \rfor Geeks"
6. \v : this option is used to create vertical tab spaces.
Example: echo -e "Geeks \vfor \vGeeks
7. \a : alert return with backspace interpreter ‘-e‘ to have sound alert.
Example: echo -e "\aGeeks for Geeks
8. -n: this option is used to omit echoing trailing newline.
Example: echo -n "Geeks for Geeks"

9. Print "Hello All": For printing text "Hello All!" on the terminal, we can use the below command:

Example: $ echo "Hello All!"

10. Print specific types of files: For example, if we wish to print every '.c' file, we can apply the below command:

Example: $ echo *.txt


➢ bc command in unix: bc command is used for command line calculator. It is similar to

basic calculator by using which we can do basic mathematical calculations.

Syntax:
bc [ -hlwsqv ] [long-options] [ file ... ]
o Options:
-h, {- -help } : Print the usage and exit
-i, {- -interactive } : Force interactive mode
-l, {- -mathlib } : Define the standard math library
-w, {- -warn } : Give warnings for extensions to POSIX bc
-s, {- -standard } : Process exactly the POSIX bc language
-q, {- -quiet } : Do not print the normal GNU bc welcome
-v, {- -version } : Print the version number and copyright and quit

1. Arithmetic Operators
Examples:
Input : $ echo "12+5" | bc
Output : 17
Input : $ echo "10^2" | bc
Output : 100
How to store the result of complete operation in variable?
Example:
Input:
$ x=`echo "12+5" | bc`
$ echo $x
Output:17

2. Assignment Operators : The list of assignments operators supported are:


• var = value : Assign the value to the variable
• var += value : similar to var = var + value
• var -= value : similar to var = var – value
• var *= value : similar to var = var * value
• var /= value : similar to var = var / value
• var ^= value : similar to var = var ^ value
• var %= value : similar to var = var % value
Examples:
Input: $ echo "var=10;var" | bc

Output: 10

Input: $ echo "var=10;var^=2;var" | bc

Output: 100
How to store the result of complete operation in variable?
Example:
Input:
$ x=`echo "var=500;var%=7;var" | bc`
$ echo $x
Output:3

3. Increment Operators: There are 2 kinds of increment operators:


• ++var : Pre increment operator, variable is increased first and then result of variable is stored.
• var++ : Post increment operator, result of the variable is used first and then variable is
incremented.
Examples:
Input: $ echo "var=10;++var" | bc

Output: 11

Input: $ echo "var=10;var++" | bc

Output: 10

4. Decrement Operators :There are 2 kinds of decrement operators:


• – – var : Pre decrement operator, variable is decreased first and then result of variable is
stored.
• var – – : Post decrement operator, result of the variable is used first and then variable is
decremented.
Examples:
Input: $ echo "var=10;--var" | bc
Output: 9
Input: $ echo "var=10;var--" | bc
Output: 10

5. Comparison or Relational Operators


Relational operators are used to compare 2 numbers. If the comparison is true, then result is 1.
Otherwise(false), returns 0. These operators are generally used in conditional statements like if.
The list of relational operators supported in bc command are shown below:

• expr1<expr2 : Result is 1 if expr1 is strictly less than expr2.


• expr1<=expr2 : Result is 1 if expr1 is less than or equal to expr2.
• expr1>expr2 : Result is 1 if expr1 is strictly greater than expr2.
• expr1>=expr2 : Result is 1 if expr1 is greater than or equal to expr2.
• expr1==expr2 : Result is 1 if expr1 is equal to expr2.
• expr1!=expr2 : Result is 1 if expr1 is not equal to expr2.
Examples:
Input: $ echo "10>5" | bc

Output: 1

Input: $ echo "1==2" | bc

Output: 0
6. Logical or Boolean Operators
Logical operators are mostly used in conditional statements. The result of the logical operators is
either 1(TRUE) or 0(FALSE).
• expr1 && expr2 : Result is 1 if both expressions are non-zero.
• expr1 || expr2 : Result is 1 if either expression is non-zero.
• ! expr : Result is 1 if expr is 0.
Examples:
Input: $ echo "10 && 5" | bc

Output: 1

Input: $ echo "0 || 0" | bc

Output: 0

Input: $ echo "! 0" | bc

Output: 1

7. Mathematical Functions (example at previous blank page)


The built-in math functions supported are :
• s (x): The sine of x, x is in radians.
• c (x) : The cosine of x, x is in radians.
• a (x) : The arctangent of x, arctangent returns radians.
• l (x) : The natural logarithm of x.
• e (x) : The exponential function of raising e to the value x.
• j (n,x) : The bessel function of integer order n of x.
• sqrt(x) : Square root of the number x. If the expression is negative, a run time error is
generated.
In addition to the math functions, the following functions are also supported :

• length(x) : returns the number of digits in x.


• read() : Reads the number from the standard input.
• scale(expression) : The value of the scale function is the number of digits after the decimal
point in the expression.
• ibase and obase define the conversion base for input and output numbers. The default for both
input and output is base 10.
• last (an extension) is a variable that has the value of the last printed number.
8. Conditional Statements
Conditional Statements are used to take decisions and execute statements based on these decisions. bc
command supports the if condition.

Syntax:
if(condition) {statements} else {statements}
Example:
Input: $ echo 'n=8;m=10;if(n>m) print "n is greater" else print "m is greater" ' | bc -l

Output: m is greater

10. Iterative statements : bc command supports the for loop and while loop for doing iterations.
Syntax:
for(assignment; condition; updation)
{
statements.....
.......
........
}

OR

while(condition)
{
statements.....
.......
........
}

Examples:
Input: $ echo "for(i=1; i<=10; i++) {i;}" | bc
Output:
1
2
3
4
5
6
7
8
9
10
Input: $ echo "i=1;while(i<=10) {i; i+=1}" | bc
Output:
1
2
3
4
5
6
7
8
9
10

10. Functions : Functions provide a method of defining a computation that can be executed later.
Functions in bc always compute a value and return it to the caller. Function definitions are “dynamic” in the
sense that a function is undefined until a definition is encountered in the input. That definition is then used
until another definition function for the same name is encountered. The new definition then replaces the
older definition.
Syntax:
define name (parameters)
{
statements.......
.......
........
return statement

➢ Change or set Password: The passwd command changes passwords for user accounts.

SYNOPSIS : passwd [options] [LOGIN]

Example-1: Change your own password: $ passwd

output:

$ passwd
Changing password for ubuntu.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

Example-2:

Change the password for the user named username: $ sudo passwd username

output:

$ sudo passwd user1


Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

Example-3:

Check the status of the password for the user named user1: $ sudo passwd -S user1

output:

user1 P 05/13/2014 2 365 7 28

o Forcing user for changing the password at the next login

Linux passwords by default never expire for any users. But, we can also force the users for changing the
password they log in by CLI or GUI methods next time. The syntax is as follows:
1. $ sudo passwd -e {username}
2. $ sudo passwd --expire {username}

Let us expire the password of an account immediately, we can use the following command:

1. $ sudo passwd -e karishma

o Lock and unlock user passwords

• Lock password:

By using the following command, we can lock the user password:

1. $ sudo passwd -1 {username}


• Unlock password:

We can use the following command for unlocking a password:

1. $ sudo passwd -u {username}

Example-7:

Expire user1's password. The next time he logs in, he will be required to set a new password.

$ sudo passwd -e user1

output:

passwd: password expiry information changed.

➢ `who` Command:
The who command is used to get information about currently logged-in users on the
system.
Syntax of who Command:
who [options] [filename]
➢ Examples of who Command
1. The who command displays the following information for each user currently logged in
to the system if no option is provided :
1. Login name of the users
2. Terminal line numbers
3. Login time of the users into the system
4. The remote host name of the user
hduser@mahesh-Inspiron-3543:~$ who
hduser tty7 2018-03-18 19:08 (:0)
2. To display host name and user associated with standard input such as keyboard
hduser@mahesh-Inspiron-3543:~$ who -m -H
NAME LINE TIME COMMENT
3. To show all active processes which are spawned by INIT process
hduser@mahesh-Inspiron-3543:~$ who -p -H
NAME LINE TIME PID COMMENT
4. To show status of the users message as +, – or ?
hduser@mahesh-Inspiron-3543:~$ who -T -H
NAME LINE TIME COMMENT
hduser + tty7 2018-03-18 19:08 (:0)
5. To show list of users logged in to system
hduser@mahesh-Inspiron-3543:~$ who -u
hduser tty7 2018-03-18 19:08 01:16 3357 (:0)
6. To show time of the system when it booted last time
hduser@mahesh-Inspiron-3543:~$ who -b -H
NAME LINE TIME PID COMMENT
system boot 2018-03-18 19:07
7. To show details of all dead processes
hduser@mahesh-Inspiron-3543:~$ who -d -H (NO dead process in this case)
NAME LINE TIME IDLE PID COMMENT EXIT
NAME LINE TIME IDLE PID COMMENT EXIT
8. To show system login process details
hduser@mahesh-Inspiron-3543:~$ who -l -H
NAME LINE TIME IDLE PID COMMENT
LOGIN tty1 2018-03-18 19:07 3073 id=tty1
9. To count number of users logged on to system
hduser@mahesh-Inspiron-3543:~$ who -q -H
hduser
# users=1
10. To display current run level of the system
hduser@mahesh-Inspiron-3543:~$ who -r
run-level 5 2018-03-18 19:07
11. To display all details of current logged in user
hduser@mahesh-Inspiron-3543:~$ who -a
system boot 2018-03-18 19:07
LOGIN tty1 2018-03-18 19:07 3073 id=tty1
run-level 5 2018-03-18 19:07
hduser + tty7 2018-03-18 19:08 01:13 3357 (:0)
12. To display system’s username
hduser@mahesh-Inspiron-3543:~$ whoami
hduser
13. To display list of users and their activities
hduser@mahesh-Inspiron-3543:~$ w
20:39:20 up 1:32, 1 user, load average: 0.09, 0.06, 0.07
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
hduser tty7 :0 19:08 1:32m 38.95s 0.19s /sbin/upstart -
14. To display user identification information
hduser@mahesh-Inspiron-3543:~$ id
uid=1001(hduser) gid=1001(hadoop) groups=1001(hadoop), 27(sudo)

2. Using `user` Command to List Current Logged-in Users in Linux


It also provides information about logged-in users. You can list the currently logged-in users.
Users

3. Using `w` Command to List Current Logged-in Users in Linux


The `w` command provides a wealth of information about currently logged-in users, including their
usernames, terminal IDs, remote IP addresses, login times, CPU usage, and more.
w
4. Using `last` Command to List Current Logged-in Users in Linux
The `last` command shows a list of recently logged-in users, along with the times they logged in
and out. By running `last` without any options, you can see a historical log of user logins.
last
5. Using `finger` Command to List Current Logged-in Users in Linux
The `finger` command provides detailed information about a particular user or all users currently
logged in. For information on a specific user, use `finger <username>`
finger
6. Using `top` Command to List Current Logged-in Users in Linux
While primarily known for displaying real-time system statistics, the `top` command also lists the
currently logged-in users. To view the user list, run `top` and then press `u`. This will show a list of
logged-in users and their associated processes.
top

You might also like