0% found this document useful (0 votes)
33 views9 pages

Essential UNIX Commands Guide

This document provides an overview of basic UNIX commands organized into categories such as file commands, directory commands, terminal commands, help commands, and information commands. It describes commands like ls, cd, pwd, cat, more, less, mkdir, rmdir, clear, echo, man, history, and hostname. It also covers permissions and processes, and UNIX filters like grep, sort, head, tail, find, split, cmp, and diff. The document was prepared by an instructor at FAST-NUCES Peshawar as part of an operating systems lab covering basic UNIX commands.

Uploaded by

Muhammad Majid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views9 pages

Essential UNIX Commands Guide

This document provides an overview of basic UNIX commands organized into categories such as file commands, directory commands, terminal commands, help commands, and information commands. It describes commands like ls, cd, pwd, cat, more, less, mkdir, rmdir, clear, echo, man, history, and hostname. It also covers permissions and processes, and UNIX filters like grep, sort, head, tail, find, split, cmp, and diff. The document was prepared by an instructor at FAST-NUCES Peshawar as part of an operating systems lab covering basic UNIX commands.

Uploaded by

Muhammad Majid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Operating Systems Lab

Lab # 03
BASIC UNIX COMMANDS

1. Some Basic UNIX Commands

i. FILE COMMANDS

touch Create a new


file.
Usage: touch <filename>
Usage:
cp Copy files.

Usage: cp [options] <source-filename> <destination-filename>


cp [options] <source-filepath > <destination filepath>

mv Move or Rename files or directories.


Usage: mv [options] <old-filepath> <new-filepath>
mv [options] <old-filename> <new-filename>
Options: -i query user for confirmation.
rm Remove
files.
Usage: rm [options] <filname>

-i query user for confirmation.


cat View complete file content.

cat <filename>
more View file contents in sections determined by the size of the terminal.

Usage: more <filename>


less View file contents in sections determined by the size of the terminal.

Has more options and search features than more.


Usage: less [options] <filename>

ii. DIRECTORY COMMANDS

cd Change directory.
Usage: cd <filename>

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar


Operating Systems Lab

Eg: cd my-directory
cd go to home directory
cd .. go up one directory

pwd Print working directory on the terminal.


ls List the content of a directory.

Usage: ls [options] or ls [options] <directory-path>


Options: -l list all files in long format.
(permissions, users, filesize,date, and time are displayed).
-a list all files including those beginning with a “.”
-F list files distinguishing
directories/ executables* symbolic links@

mkdir Create a new directory.

Usage: mkdir <directory-path>


rmdir Remove a directory if its empty.

Usage: rmdir <directory-path>

rm -rf directory_name will remove non empty directory

iii. TERMINAL COMMANDS

clear Clears the terminal.

echo: Write a string to standard output. Usage: echo


“string” or

echo ‘string’

iv. HELP COMMANDS

man Displays the manual page for the selected command.


Usage: man <command-name>

help Opens the default web browser in the andrew unix help web site.
[Link]

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar


Operating Systems Lab

Page

v. INFORMATION COMMANDS

history Lists the commands typed during the session.

Options: -r displays the list in reverse.


hostname Displays the computer’s or server’s name on the terminal.
who Displays who is on the system.
who am i Displays the invoking user.
wc Counts and displays the number of lines, words and characters of a
file.
Usage: wc [options] <filename>
Options: - count character only.
c
-lcount lines only.
-w count words only.
date Exercise >> to be completed by students.

cal Exercise >> to be completed by students.

whatis Displays the command description.

Usage: whatis <command>


whereis Exercise >> to be completed by students.

which Exercise >> to be completed by students.

id Displays the user id and the group id of the invoking user.

tty Displays user’s terminal name.

vi. USEFUL CSHELL SYMBOLS


| Pipe the output of a command to be processed by another command.
Usage: command1 |command2
Eg: ls -l | more
> Redirect output........ to file (overwrite ).
Usage: command > filename
Eg: wc filename > new-file

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar


Operating Systems Lab

>> Append (the result of the command) to the end of the file.

Usage: command >> file-name


Eg: pwd >> existing-file
< Take the input for the command from a file.

Usage: command1 < filename.


& Run process in the background so that the shell remains active.

Usage: program-name &


program-name filename &
; Separate commands on the same line.

Usage: command1 ; command2


Eg: pwd ; ls
! The history commands.

!! Redo last command.


!str Redo the last command that starts with str.
!23 Redo the 23rd command.
!-2 Redo the (last command -2)
^ Quick modifier for the last command.

Usage: ^mistake^correction.
&& The logical and symbol : execute first command then if successful,

the second command.


Usage: <command1> && <command2>
|| The OR symbol : executes the first command or, if it fails, the second

command.
Usage: <command1> || <command2>
./ Runs a compiled program.

Usage: ./ program-name

vii. PERMISSIONS AND FILE STORAGE (UNIX)

chmod Set the permission on a file or a directory.


Usage: chmod [options] <who> <opcode> < permission> <file-
name>
Options: - Recursively updates permisions within a directory
R
structure.
Who: u User

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar


Operating Systems Lab

g Group
o other
a All
Opcode: + add permission.
- remove permission.
Permission:

r Read
w Write
x execute
Eg: chmod a +rwx public-file
adds permissions of read write and execute to all.
Eg: chmod go -wx my-file
removes write and execute to group and others.
passwd Change the password.

df Displays the amount of free and used disk space.

du Displays the amount of disk usage.

viii. PROCESSES

ps Displays the active processes.


Includes the process number, process name and process time.
Options: -a
kill Terminates a process.

Usage: kill [options] <process-number>


Options: -9 absolute kill.

ix. UNIX FILTERS

fgrep A variation of grep that maches a text-string and does-not support

regular expressions.
Eg: fgrep <string> <file-name>

spell Exercise >> to be completed by students

sort Exercise >> to be completed by students

head Exercise >> to be completed by students

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar


Operating Systems Lab

tail Exercise >> to be completed by students

find Search the system for filenames.

Usage: find <pathname> <condition>


Eg: find /home/hoda -name seed
split Splits a file into several files of equal length.

Usage: split [options] <filename> <outfile>.


Options: - specifies the number of lines per file.
n
cmp Compare 2 files.

Usage: cmp <file1> <file2>


diff Reports the lines that differ between 2 files

Usage: diff <file> <file2>

x. Users and Groups

useradd <Username>
passwd <Username>
login <Username>
logout <Username>
groupadd <Groupname>
usermod -a -G <Groupname> <Username>
usermod -G <Groupname> <Username>
id <Username>
chown <username> <filename>

xi. File and Directory Compression

sudo apt-get install zip gzip tar

zip my_arch.zip my_folder

uzip my_arch.zip
Use the following command to compress an entire directory or a single file on Linux. It’ll also
compress every other directory inside a directory you specify–in other words,

tar -czvf [Link] /path/to/directory-or-file

Here’s what those switches actually mean:

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar


Operating Systems Lab

-c: Create an archive.


-z: Compress the archive with gzip.
-v: Display progress in the terminal while creating the archive, also known as “verbose” mode.
The v is always optional in these commands, but it’s helpful.
-f: Allows you to specify the filename of the archive.

Use bzip2 Compression Instead

tar -cjvf [Link].bz2 stuff

Extract an Archive

Once you have an archive, you can extract it with the tar command. The following command will
extract the contents of [Link] to the current directory.

tar -xzvf [Link]

It’s the same as the archive creation command we used above, except the -x switch replaces the -
c switch. This specifies you want to extract an archive instead of create one.

You may want to extract the contents of the archive to a specific directory. You can do so by
appending the -C switch to the end of the command. For example, the following command will
extract the contents of the [Link] file to the /tmp directory.

tar -xzvf [Link] -C /tmp

If the file is a bzip2-compressed file, replace the “z” in the above commands with a “j”.

tar -xjvf [Link].bz2

xii. Installation of Packages from Repositories (APT-GET)

There are literally thousands of Ubuntu programs available to meet the needs of Ubuntu users.
Many of these programs are stored in software archives commonly referred to as repositories.
Repositories make it easy to install new software, while also providing a high level of security,
since the software is thoroughly tested and built specifically for each version of Ubuntu.

The four main repositories are:

Main - Officially supported software.

Restricted - Supported software that is not available under a completely free license.

Universe - Community maintained software, i.e. not officially supported software.

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar


Operating Systems Lab

Multiverse - Software that is not free.

The apt or Advanced Packaging Tool is a package manager. The apt keeps a list of packages that
it can install in its cache (or repository). This cache has information on where the software is (ie
the URL) located, what all additional software is required to run that software and the version it
can install on the current system.

So when you say "sudo apt-get install <package>", it checks its repository for the packages name.
If the package is available in the list, it then proceeds to locate, download and install the software
and all the required dependencies.

Exercise 1

I. The boxes in blue are directories. The boxes in gray are _files. Each _files should contain a
random mark of your liking. Once done, delete all the _files/directories that you have created.
II. Count the total number of commands you entered to do this job. I managed using 6 commands.

Exercise 2

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar


Operating Systems Lab

i. How are we going to change it using the _mv_ command so that we get the directory tree as
below?

ii. Change your directory so that your current directory is _Physics_.


iii. From here, change your directory in only one command such that your current directory
becomes _subject. From _subject_, issue only one command such that the directory _physics_
is deleted.

Prepared By: Kaleem Nawaz Khan (Instructor CS) FAST-NUCES Peshawar

Common questions

Powered by AI

Software repositories in Ubuntu serve as centralized hubs that store a collection of software packages available for installation. They simplify software management by allowing easy installation, updates, and maintenance of applications directly from trusted sources. These repositories are categorized into Main, Restricted, Universe, and Multiverse, reflecting varying levels of support and license types. Security is ensured through thorough testing of software before inclusion in the repositories, safeguarding users against vulnerabilities associated with unverified software sources . This structured repository system ensures that users can access reliable software versions that are compatible and secure for their system version .

'Fgrep' is a variant of 'grep' that matches fixed strings rather than regular expressions, making it suitable for simple substring searches where pattern complexity is not required, such as searching for specific keywords in logs. It processes searches faster by avoiding the complexity of regular expression parsing. In comparison, 'grep' and 'egrep' support regular expressions, offering more flexibility for pattern matching and searching complex patterns within files. 'Egrep' additionally supports extended regular expressions, enabling sophisticated text processing tasks. While 'fgrep' is optimal for speed and simplicity, 'grep' and 'egrep' serve complex text-processing needs effectively .

The 'chmod' command manages file permissions in UNIX by allowing users to modify read, write, and execute permissions for user categories (user, group, others) on files or directories. This control is essential for maintaining security and ensuring that only authorized users can access or modify files. The '-R' option enables recursive permission changes within a directory structure, impacting all files and subdirectories. While powerful, this option requires careful use to prevent inadvertently granting or revoking permissions on a large scale, potentially leading to security vulnerabilities if used improperly .

In a build script, one could use '&&' and '||' operators to manage dependencies efficiently. For instance, compiling a program with 'make && echo "Build successful" || echo "Build failed"' would run 'make', and only on success, print "Build successful"; if 'make' fails, it prints "Build failed". This chaining provides clear outcomes without scripting additional conditional logic, optimizing the process by reducing manual oversight and automatically handling different outcomes . Such use ensures a streamlined workflow by linking command execution to success or failure states, enhancing error handling in automated tasks .

The 'cd' command changes the current directory to the specified directory path provided by the user. For instance, 'cd /var/www' would move directly to that directory. In contrast, 'cd ..' navigates one level up in the directory hierarchy without specifying a path, and 'cd ~' moves to the user's home directory using a shortcut notation, enhancing efficiency for common navigational paths . These shortcut commands are useful for quick navigation and do not require the user to remember or type long directory paths .

The '-v' or verbose mode option, when used with the 'tar' command, improves user experience by displaying the progress of the archiving process in the terminal. This feature allows users to see a list of files being processed, making the operation transparent and providing reassurance that the correct files are being archived. It is particularly useful in large-scale operations to monitor progress and diagnose potential issues, though it is optional and increases terminal output verbosity .

Piping ('|') in UNIX allows the output of one command to be used as the input for another, facilitating powerful command chaining and transformative data handling in shell scripting. For example, 'ls -l | grep "Jan"' lists files modified in January by passing the detailed directory listing through 'grep'. This capability enables complex data processing workflows by combining simple commands in sequence, enhancing scripts' modularity and reducing the need for intermediate files or manual intervention. With piping, scripts can efficiently handle and transform data on-the-fly, streamline processes, and improve script performance .

'Less' is preferred over 'more' when navigating large files due to its ability to move backward and forward through a file without reloading the content, which 'more' cannot do. Additionally, 'less' supports search functions and other features such as viewing non-printing characters, making it more versatile for detailed file examination. When dealing with large or complex files, 'less' provides superior navigation and control over file content display .

The 'cmp' command is advantageous for quickly identifying byte-level differences between two files, making it efficient for binary file comparison or locating the first point of difference. However, it does not detail the content of these differences. In contrast, 'diff' provides a line-by-line comparison, displaying specific changes between text files, which is useful for understanding modifications or resolving conflicts in source code. 'Diff' offers greater insight into file changes but can be slower with large files compared to 'cmp' . Choosing between the two depends on whether a quick binary check or detailed comparison is needed .

The 'rm -rf' command is used to remove directories and their contents recursively, including non-empty directories, without prompt for confirmation unless paired with the '-i' flag. In contrast, 'rmdir' only removes empty directories, making it safer but less flexible for batch deletions . By requiring no confirmation by default, 'rm -rf' can lead to data loss if used carelessly, whereas 'rmdir' prevents accidental deletion of important files since it fails if the directory contains files. 'rm -rf' is powerful for extensive cleanup operations, but care must be taken when using it to avoid unintended file loss .

You might also like