0 ratings0% found this document useful (0 votes) 31 views31 pagesWorking With Command
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Unit III Working with Command
BSc. III Sem. V
Prepared by Dr. U. S. Junghare
Introduction:
‘A command is an instruction given to our computer by us to do whatever we want The
Linux command is a utility of the Linux operating system. All basic and advanced tasks can be
done by executing commands. The commands are executed on the Linux terminal. The terminal is
a command-line interface to interact with the system, which is similar to the command prompt in
the Windows OS. Commands in Linux are case-sensitive,
Commands are executed by typing in at the command line followed by pressing enter key,
‘This command further passes to the shell which reads the command and execute it. Shell isa
method for the user to interact with the system. Default shell in Linux is called bash (Bourne-
Again Shell).
Linux provides a powerful command-line interface compared to other operating systems
such as Windows and MacOS. We can do basic work and advanced work through its terminal. We
can do some basic tasks such as creating a file, deleting a file, moving a file, and more. In addition,
wwe can also perform advanced tasks such as administrative tasks (including package installation,
user management), networking tasks (ssh connection), security tasks, and many more.
Directory Commands:
Directory Description
Command
pwd ‘The pwd command stands for (print working directory). It
displays the current working location or directory of the
user. It displays the whole working path starting with /. It is
a built-in command.
Is The Is command is used to show the list of a folder. It will
list out all the files in the directed folder.
cd ‘The cd command stands for (change directory). It is used to
change to the directory you want to work from the present
directory
With mkdir command you can create your own directory.
‘The rmdir command is used to remove a directory from your
system,pw
The ‘pwd,’ which stands for “print working directory”. In this article, we will delve into
the ‘pwd’ command, exploring its functionality, usage, and various examples. It prints the path of
the working directory, starting from the root. pwd is shell built-in command(pwd) or an actual
binary(/bin/pwd).
The basic syntax of the ‘pwd’ command
pwd [options]
This command doesn’t have any arguments or options, but it can accept flags for specific
behavior
How to Display the Current Working Directory in Linux:
a, Displaying the Current Working Directory Using Built-in pwd (pwd):
To print the current working directory, simply enter:
file Edit View Terminal Tabs Help
Pe eae)
Rites year:
Perea ea eee
Ariryeieec ATs
Par iecc cL eaC ree me
etoats
Beene Se EAC Ee
3.1 Display the Current Working Directory
‘* The output will be the absolute path of your current location in the file system.
In the given example the directory /home/shital/logs/ is a symbolic link for a target
directory /var/logs/
b. Displaying the Current Working Directory Using Binary pwd (/bin/pwd):
file Edit View Terminal Tabs Help
Serre Stree yr)
~/Logs$ /bin/pwd
/var/Log
shital@debian:~/logs$ /bin/pwd
cya res OAT
shital@debian:~/logs$
Fig. 3.2 Display the Current Working Directory* The default behavior of Built-in pwd is the same as pwd -L. Using “pwd -L” to obtain the
symbolic path of a directory containing a symbolic link
© The default behavior of /bin/pwd is the same as pw -P. Utilizing “pwd -P” to display the
actual path, ignoring symbolic links.
¢. The $PWD Environment variable.
The SPWD environment variable is a dynamic variable that stores the path of the current
working directory. It holds the same value as ‘pwd -L’ — representing the symbolic path
file Edit View Terminal Tabs Help
Str Sen revatrry
Cy rac eAtl ts
Eipee Ce eu reac es
Fig. 33 $PWD
‘* Executing this command prints the symbolic path stored in the SPWD environment
variable
Is command:
The command “Is” is a Linux shell command that lists directory contents of files and
directories. It provides valuable information about files, directories, and their attributes.
Syntax of “Is' command in Linux
1s [option] [file/directory]
« ‘Is’ will display the contents of the current directory.
© By default, ‘Is’ lists files and directories in alphabetical order.
‘Commonly Used Options in “Is command in Linux
[Options Description
F) known as a long format that displays detailed information about files and
directories.
“a Represent all files Include hidden files and directories in the listing
t Son files and directories by their last modification time, displaying the most
recently modified ones first.
known as reverse order which is used to reverse the default order of listing.
‘Sort files and directories by their sizes, listing the largest ones first.
List files and directories recursively, including subdirectories.
known as inode which displays the index number (inode) of each file anddirectory,
“i known as group which displays the group ownership of files and directories,
nstead of the owner.
ch Print file sizes in human-readable format (e.g., IK, 234M, 2G).
-d List directories themselves, rather than their contents
ed command:
The ‘ed’ command allows users to change their current working directory within the file
system. The basic syntax of the “ed” command is as follows:
ed [directory]
Here, replace [directory] with the destination directory path you want to navigate to. If no
directory is specified, ‘ed’ will take you to your home directory by default, To move inside a
subdirectory in Linux we use the CD Linux Command.
Here, replace [directory_name] with the desired directory you want to move in.
cd [directory_name]
For Example:
If we want to move to a subdirectory named “Documents”
cd Documents
raghvendra@raghvendra-Inspiron-15-3567: ~/Documents
ee Cae
are
By using */ as an argument in “cd we can change the directory to the root directory. The root
directory is the first directory in your filesystem hierarchy,
cd/Following command is used to move inside a directory from a directory. Here, replace
“dir_l/dir_2/dir_3” with the subdirectory name or location you want to move in.
ed dir_U/dir_2/dir_3
*~ This argument is used in the “ed command to change the directory to the home directory from
any location in the Linux System.
cd~
We can also pass the “cd command with no arguments, which will eventually land us in our home
directory.
cd
We use *... this as an argument in the *cd* command which is
of the current directory, or the directory one level up from the current directory.
parent directory.
ed.
used to move to the parent directory
“. represents the
‘This command is used to navigate to a directory with white spaces. Instead of using double quotes,
‘we can use single quotes then also this command will also work. Here, replace “dir name” with
the directory name you want.
cd "dir name"
For Example:
If we want to move to “dir name
“My songs”. We use the following command.
ed "My songs"
We can also use *\ in between if we don’t want to use double or single quotes.
ed My\ songs
mkdir Command:The ‘mkdir’ command is like a magic wand for creating folders super easily. ‘mkdir’ stands
for “make directory,” and it helps you organize your computer stuff by creating folders with just
one command. This command can create multiple directories at once as well as set the permissions
for the directories.
Syntax of ‘mkdir* Command in Linux
mkdir [option
[directory_name]
Here, replace [directory_name] with the desired name of the directory you want to create.
Options and their Practical Implementation in “mkdi
1) “-help* Option in “mkdir Command in Linux
It displays help-related information and exits.
Syntax:
mkdir --help
2)*-version’ Option in “mkdir Command in Linux
It displays the version number, some information regai
Syntax:
ing the license and exits,
mkdir --version
3) -¥ or verbose” Option in to Create Directory in Linux
It displays a message for every directory created.
Syntax:
mkdir -v [directories]
Here we have used “Is* command to display all files and directories,
4) *-p* Option to Create Directory in Linux
A flag which enables the command to create parent directories as necessary. If the
directories exist, no error is specified.
Syntax:
mkdir -p [directories]
‘Suppose you execute the following command:
mkdir -p first/second/third
If the first and second directories do not exist, due to the -p option, mkdir will create thesedirectories for us. If we do not specify the -p option, and request the crea
parent directory doesn’t exist,
ion of directories, where
If we specify the -p option, the directories will be created, and no error will be reported. Following
is the output of one such execution, We've also provided the -v option, so that we can see it in
action
Sen
5) “-m’ Option to Create Directory in Linux
This option is used to set the file modes, i.e. permissions, etc. for the created directories.
‘The syntax of the mode is the same as the “chmod” command.
Syntax:
mkdir -m
=rwx [directories]
The above syntax specifies that the directories created give access to all the users to read
from, write to and execute the contents of the created directories. You can use ‘ar’ to only allow
all the users to read from the directories and so on.
rmdir command:
The “rmdir” command in Linux is specifically designed to remove empty directories.
Unlike the rm command, which can delete both files and directories, rmdir focuses solely on
directories. It is a straightforward tool but nonetheless crucial for maintaining a tidy directory
structure on your system.
Basic Syntax‘The basic syntax of the rmdir command is:
rmdir [option] directory_name
“rmdir” Command in Linux With Examples
‘mmdir” command is similar to the rm command, but “rmdir” only removes empty directories. So
first, we will use the help flag to list down all the available options for the “rmdir” command:
rmdir —help
‘The above command displays the various options such as:
Understanding Options
‘© -p, parents: This option enables the removal of parent directories as well if they
become empty after removing the specified directory. It essentially removes the
directory along with its parent directories if they become empty.
erbose: When used, this option displays a message for each
providing feedback on the action being performed.
‘+ ~ignore-fail-on-non-empty: By default, “rmdir” fails if the directory is not empty.
However, this option forces “rmdir” to ignore such failures and proceed with the
removal.
‘+ -version: This option displays the version information and exit.
irectory processed,
‘we will remove LINUX, INFO, and DETAIL directories through the following command:
rmdir LINUX INFO DETAIL.
You can use the -p option with the “rmdir” command to delete a directory, including all thesubdirectories:
For example, we will delete the LINUX directory,
following command:
ncluding all its all ancestors, through the
rmdir -p LINUX/mydirl/mydir2/mydir3
If you want the terminal to display the message after removing the directory, you can use the -v
option with the rmdir command:
Let’s now delete the LINUX, INFO, and DETAIL directories and display the message after their
successful removal:
rmdir -v LINUX INFO DETAIL,
This command is removing directory, ‘LINUX’
Also removing directory, INFO’
Also removing directory, DETAIL!
You can delete multiple directories if they have the same expressions by using the * in the
rmdir command. For example, let’s remove all those directories which contain LINUX in their
name:
rmdir -v LINUX*
Renaming directory (my, find, rename):
In Linux, the renaming process of a folder or directory is not done with a traditional rename
command; instead, it is done through the 'my' command. The ‘mv' command is a multi-purpose
command. It is not just limited to move files and directories, but it can also be used for renaming
the files and directories.
It is important to keep the file system structured to ease access to the data. Sometimes, we
create some temp files, and later we need to rename them. In such cases, it is a handy tool
However, the directories can be renamed using various commands and utilities such as mv
command, find command, rename command, using Bash, and more.
Renaming directories using “mv” command:
Basically, the “my” command is used to move files, but we can also rename the folders
and directories by it. We can simply rename the folders by executing the mv command, followed
by the old folder name and new folder name, respectively.
For example, T
‘To rename a folder named as 'Old_folder' to 'New_folder,’ execute the command as follows:my Old_folder New_folder
‘The above command will rename the folder
Renaming directories using find command
In some cases, we don't know exactly where the required directories are located. The find
command assists us in finding and locating the directories in the Linux system. To find the
directories use the find command with the ‘type’ option to look for directories from the file system,
‘We can rename them by executing the mv command with the '-exeedir" option.
For example,
‘To rename the 'New_folder’ directory, execute the below command to find i
find . depth -type d -name "New_folder"
The above command will locate the directory from the file system. If you don’t remember
the exact directory name, you can type the matching directory name. Consider the below output
Irind . depth -type d -nane "New folder’
Now, to rename the directory, execute the mv command with '-execdir’ option as follows
find . -depth -type d -name New_folder -execdir my {} Directory \;
Renaming directories using the rename command
The rename command is a built-in utility to rename the files and directories for the most
Linux distribution. However, it may not be directly available for all the Linux distribution Instead
of the “my” command, we can rename files using the rename command, It allows us to rename
multiple files and directories
We can rename multiple directories together, such as rename all the text directories into
any other format, rename all the directories which are in lowercase to uppercase, and more.
Syntax:
rename File Commands:
“file” command:
“file” command is used to determine the type of a file. File type may be of human-readable
(e.g. ‘ASCII text’) or MIME type (e.g. ‘text/plain; charset=us-ascii’).
Filesystem Test: This testis based on the result which returns from a stat system call. The program
verifies that if the file is empty, or if it’s some sort of special file. This test causes the file type to
be printed.
Magic Test: These tests are used to check for files with data in particular fixed formats.
Language Test: This test search for particular strings which can appear anywhere in the first few
blocks of a file.
Linux “file” Command Options
Option Funetion
file-s Used for special files.
file* Used to list types of all the fies.
Mie faieeeongy Used to list types of all the files from mentioned directory.
feetNoger lo al he ls starting Fo pbs preset wine en
Syntax:
file [option] [filename]
Example: Command displays the file typefile email.py
file name.jpeg
file Invoice.pdf
file exam.ods
file videosong.mp4
Options of “file” command:
1) -b, -brief: This option is used to display just file type in brief mode.
Syntax:
file -b filename
file -b email. py
file -b input.txt
file -b os.pdf
Here, we can see that file type without filename.
2)* option: This option is used to display the all files’s file type.
file *
‘The output shows all files in the home directory
3) Directory name/* option: This option is used to display all files filetypes in particular directory.
‘Syntax:
file directoryname/*
Example:
file work/*
‘The output shows all files in a particular directory
4) [range]* option: To display the file type of files in specific range.
Syntax:
file [range]*
Example:
file [a-z]*
5) -s option: This option is for special files.
Syntax:
file -s filename
Example:
file /dew/sdafile -s /dew/sda
file /dev/sdaS
file -s /dev/sdaS6) filenames: This option Displays file types of multiple files
Syntax:
file filenames
Example:
file input.txt.local Desktop
“touch” command:
The “touch command” is a standard command used in the UNIX/Linux operating system
which is used to create, change and modify the timestamps of a file. Basically, there are two
different commands to create a file in the Linux system which are as follows:
“touch” command:
Itis used to create a file without any content. The file created using the touch command is
empty. This command can be used when the user doesn’t have data to store at the time of file
creation.
Using touch Command Initially, we are in the home directory and this can be checked using,
the pwd_command. Checking the existing files using the command Is and then long listing
command({l) is used to gather more details about existing files. As you can see in the below figure
there are no existing files.
Create an Empty Files by Using “touch” Command:
You can create a single file at a time using touch command.
‘The basic syntax of the “touch” command is:
touch [options] file_name
The file which is created can be viewed by Is command and to get more details about the
file you can use long listing command II or Is -1 command. Here file with name ‘File1” is created
using touch command.
Create Multiple Empty Files
“touch” command can be used to create multiple numbers of files at the same time. These
files would be empty while creation,
‘Syntax:
touch Filel_name File2_name File3_name
Multiple files with name Doel, Doc2, Doc3 are created at the same time using touch
command here.Options and Pratical Implementation of How to Create an Empty File in Linux:
Options Description
“a This option changes the access time only.
Ea Suppresses file creation if the file does not exist.
-d Sets the access and modification times using the specified STRING.
-m This option changes the modification time only.
7 Uses the access and modification times from the reference file.
1)’-a° option in “touch” Command to Only Update Access Time
This command is used to change access time only. To change or update the last access or
‘modification times of a file touch -a command is used.
Syntax:
touch -a fileName
2) Creating an Empty File Using *-c’ option in “touch” Command
This command is used to check whether a file is ereated or not. If not created then don’t
create it, This command avoids creating files,
Syntax:
touch -c fileName
3)-€ -¢° option in touch’ Command
‘This is used to update access and modification time.
syntax:
touch -c-d fileName4)-m* option in touch’ Command to Only Update Modification Time
This is used to change the modification time only. It only updates last modification time.
jyntax:
touch -m fileName
5)-d° ”” option in ‘touch’ Command
‘This command is used to change only modification date.
Syntax:
touch -d "17 Mar 2023" Geek.txt
* option in ‘touch’ Command for Copying Timestamps from Another File
This command is used to use the timestamp of another file. Here Doc? file is updated with
the time stamp of File 1
oy
Syntax:
touch -r second_file_name first_file_name
7) Creating an Empty File Using °-f option in “touch” Command
‘This is used to create a file using a specified time.
Syntax:
touch -t YYMMDDHHMM fileName
“rm” command:
“tm” stands for remove here, “rm” command is used to remove objects such as files,
directories, symbolic links and so on from the file system like UNIX. To be more precise, “rm
removes references to objects from the filesystem, where those objects might have had multiple
references (for example, a file with two different names).
By default, it does not remove directories. This command normally works silently and you
should be very careful while running rm command because once you delete the files then you are
not able to recover the contents of files and directories.
1m [OPTION]... FILE,
sider 5 files having name a.txt, b.txt and so on till ext.
Sis
a.txt b.txt c.txt d.txt e.txt
Removing one file at a time
Srmatxt
Sls
bitxt caxt ditxt etxtRemoving more than one file at a time
Sim bit e.txt
Sls
datxt ectxt
Options with “rm” Command:
1) -i (Interactive Deletion):
Like in “ep”, the -i option makes the command ask the user for confirmation before
removing each file, you have to press y for confirm deletion, any other key leaves the file un-
deleted.
$rm -i d.txt
‘1m: remove regular empty file 'd.txt? y
Sis
eatxt
2) -£ (Force Deletion):
“tm” prompts for confirmation removal if a file is write protected. The -f option overrides
this minor protection and removes the file forcefully.
cp command:
‘The “cp” command is used to copy directories and files. The command contains three
primary operation modes, represented by the argument types shown to the program to copy a file
to other files, multiple files to any directory, or to copy the whole directories to other directories.
The basic syntax for copying a file using the cp command is as follows:
ep source_file destination
‘This command creates a copy of the “source_file’ at the specified “destination’. If the destination
is a directory, the file is copied into that directory.
1. Copying Between Two Files in Linux
If the “ep’ command contains two file names, it copies the contents of the first file to the
second file. If the second file doesn’t exist, itis created, and the content is copied into it. However,
if the second file already exists, it is overwritten without warning.
ep Ste_file Dest_file
IfDest_file’ does not exist, itis created.
IfDest_file” already exists, itis overwritten without any warning.
Example:* Initially, there is only one file Ca.txt’) in the directory.
The “cp* command is used to copy the contents of “a.txt™ to “batxt®
* After the command execution, both “a.txt’ and the newly created “bx coexist in the
directory.
ep atet btxt
2. Copy files to a Directory in Linux
When the cp command has one or more source file arguments and is followed by a
destination directory argument, it copies each source file to the destination directory with the same
name. If the destination directory does not exist, it is created. If it already exists, the files are
overwritten without warning.
ep Sre_filel Sre_file2 Sre_file3 Dest_directory
Example:
Suppose we have to copy three files name “a.txt*, “b.txt” and “c.txt” to a directory name “new”
ep att batxt e.txt new!
3. How to Copy Directories in Linux
In this mode, if the cp command contains two directory names, it copies all files from the
source directory to the destination directory. The *-R° option is typically used to indicate recursive
copying for directories.
ep -R Sre_directory Dest_directory
Options Available in ep Command in Linux:
‘There are many options of cp command, here we will discuss
some of the useful options:
Option | Detail
ai Interactive copying with a warning before overwriting the destination file.
b Creates a backup of the destination file in the same folder with a different name
and format.
Forces copying, even if the user lacks writing permission; deletes destination file
if necessar
-ror -R_| Copies directory structure recursively.
Preserves file characteristics (modification time, access time, ownership,
permission-bits).
* ‘Uses the * wildcard to represent all files and directories matching a pattern
2
“my” command:
Use the “mv” command to move files and directories from one directory to another.
‘The Basic Syntax for “my” command in linux is mentioned below.my [options(s)] [source_file_name(s)] [Destination_file_name]
Here,
source_file_name(s) = The name of the files that we want to rename or move.
Destination_file_name = The name of the new location or the name of the file.
Examples of “my: Command:
1, How to Rename a fil
in Linux Using “my” Command
Syntax:
my [source_file_name(s)] [Destination_file_name]
Enter your source file name in place of [source_file_name(s)] and your destination file
name in place of [Destination_file_name]
For Examph
If we have a file “name = jayesh_gfa” and want to rename it to “name = abed”,
my jayesh_gfg abed
2. How to Move a File in Linux Using “my” Command
yntax:
my [source_file_name(s)] [Destination_path]
Enter your source file nam
of [Destination_path]
place of [source_file_name(s)] and your destination path in place
For Examp!
If we have a file “name = abed” and want to move it to location “name =
/homeljayeshkumar kj”,
my abed /home/jayeshkumarzjkj/
3. How to Move Multiple files in Linux Using mv Command
syntax:
my [source_file_name_l] [source_file_name_2] [source_file_name_
[Destination_path]
Enter your source file names in place of [Source_file_name_l.....] and your destination
path in place of [Destination_path].
For Example:
If we have a file “
/home/jayeshkumanijkj””
ame = gfg_l , gf 2” and want to move it to location “name =mv gfg_l gfg_2 /home/jayeshkumar/jkj/
4, How to Move Multiple files in Linux Using my Command
Syntax:
my [source_file_name_1] [source_file_name_2] [source_file_name_
[Destination_path]
Enter your source file names in place of [source_file_name_l.....] and your destination
path in place of [Destination_path].
For Examp!
If we have a file “name = gfg_1 , gf 2” and want to move it to location “name =
home/jayeshkumarijkj””
my gfg_t gfg_2 /homeljayeshkumar/jkj/
rename command:
Changing the names of files in Linux is done using the “rename command”. It’s a tool you
use on the command line in Linux to change the names of lots of files all at once.
How to install the ‘rename Command in Linux
The availability of the rename command can vary across different Linux distributions. In this
article, we are using Debian-based systems (e.g., Ubuntu)
To install “rename” Command on Debian-based systems (e.g., Ubuntu)
sudo apt-get install rename
‘The basic syntax of the rename command is as follows:
rename [options] expression files
hese are additional flags that modify the behavior of the rename command.
Expression: This is the regular expression or Perl code that defines the transformation to be
applied to the filenames,
Files: These are the filenames or patterns of filenames that match the files to be renamed.
1) Renaming a Single File Using ‘rename’ Command in Linux
When you want to rename a single file in Linux, the rename command comes in handy.
Let’s consider an example where you have a file named “file.txt” and you want to replace it with
“name newfile.txt”
‘The basic syntax of the rename command is:
rename 's/old_pattern/new_pattern/' filename,s/old_pattern/new_pattern/: This is a Perl-style regular expression that defines the substitution
pattern. It instructs the rename command to replace occurrences of old_pattern with new_pattern.
filename: This is the name of the file you want to rename.
rename ‘sfile/newfile/"file.xt
In this example,
sffile/newfile/: This part of the command specifies that it should substitute the first occurrence of
“file” with “newfile” in the filename,
file.txt: This is the name of the file that you want to rename.
2) Renaming Multiple Files Using *rename’ Command in Linux
When dealing with the task of renaming multiple files in Linux, the rename command
becomes an indispensable tool. Let’s explore an example where several files with the “txt”
extension need to be changed to *.sh’, demonstrating the command’s syntax and execution.
Basic Syntax:
‘The syntax of the rename command for renaming multiple files is:
rename ‘s/old_pattern/new_pattern/" * extension
s Ignores symbolic links when renaming files.
v Displays which files are being renamed.
n Performs a dry run, showing the final changes without actually renaming files.
“0 Prevents overwriting existing files during the renaming process,
WV Shows version information and exits.
help Displays the help message and exits.
1) rename *-s* option:
‘This option renames the files ignoring the symbolic links.
Example:
rename -s 's/root/new/' sym.png
2) rename *-v" option
This option is used to show which files are being renamed, if there are any.
Example:
rename -v 's/jpeg/png/'*jpeg
3) rename *-n’ option‘This option comes into play when the user wants to see only the final change.
Example:
rename -n 's/png/jpeg!" *.png
4) rename *-o° option
‘This option will not be going to overwrite the existing files.
Example:
rename -0 's/jpeg/png/" *.jpeg
5) rename *-V° option
This option will show the version information and exit.
Example:
rename -V 's/jpeg/png/' *,jpeg
Printing Commands:
In Linux, the print command can refer to various commands that send text to the standard
output (usually the screen) or send documents to a printer. Below are some commonly used
commands in Linux for printing text or files, along with their syntax and examples:
1, “echo” Command
The “echo” command is used to display a line of text or a string on the standard output,
Syntax:
echo [option] [string]
Examples:
© Display a simple string:
echo "Hello, World!"
+ Display the value of a variable:
name="John"
echo "Hello, Sname!
* Use the -n option to prevent a newline character:
echo -n "This is without a newline."
“print? Command
‘The “printf” command is similar to echo but offers more formatting control. It follows the
syntax similar to the C programming language's “printf()” function.
Syntax:
printf format [arguments...]
Examples:
+ Print a formatted strin,
printf "Hello, %s!\n" "World"
+ Print numbers with specific formatting:
printf "96-10 %-8s %-4s\n" Name Age Gender
printf "%-10s %-8d %-4s\n" Alice 30 F
3. “Ip” Command
‘The “Ip” command sends files to a printer.Ip [options] [file]
+ Printa text file
Ip document.txt
+ Specify the number of copies to print:
Ip -n 2 document.txt
4. Ipr Command
The Ipr command is another way to send files to a printer
Syntax:
Ipr [options] [file]
Examples:
+ Printa file using default printer:
Ipr document.txt
+ Specify a printer and print multiple copies:
Ipr -P myprinter -#3 document.uxt
5. “cat” Command (with Redirection)
The “cat” command can display the contents of a file to the standard output or be combined.
with redirection to print the content.
Syntax:
cat [file]
Examples:
+ Display the content of a file:
cat filewwxt
+ Redirect the output to a printer:
cat file.txt | Ip
Shell &Types of Shell:
In Linux, a shell is a command-line interface that allows users to interact with the operating
system. It acts as an intermediary between the user and the kernel, enabling users to execute
commands, run scripts, manage files, and perform various administrative tasks. The shell interprets
the commands typed by the user and passes them to the operating system for execution.
‘Types of Shells in Linux:
‘There are several types of shells available in Linux, each with its own features, syntax, and.
use cases. Below are some of the most commonly used shells:
1. Bourne Shell (sh)
+ Developer: Stephen Bourne
+ Location: /bin/sh
+ Features:
© Itis the original Unix shell, developed in the 1970s.© It provides basic command execution, scripting capabilities, and control structures
(loops, conditionals).
© Itis simple, lightweight, and widely used in scripting.
+ Usage:
© Itis commonly used for shell scripting due to its compatibility across different Unix
systems.
2. Bourne Again Shell (Bash)
+ Developer: Brian Fox, Free Software Foundation
+ Location: /bin/bash
+ Featur
© Bash is an enhanced version of the Bourne Shell (sh) with added functionalities.
© It supports command-line editing, job control, shell functions, and aliases.
© It has advanced scripting capabilities with features like arrays, command
substitution, and arithmetic operations.
© Bash is the default shell in many Linux distributions (e.g., Ubuntu, CentOS),
+ Usage
© Widely used for interactive login shells and shell scripting.
© Its popularity makes it a standard shell for Linux users
3. C Shell (sh)
+ Developer: Bill Joy
+ Location: /binvesh
+ Features:
© C Shell's syntax resembles the C programming language, making it familiar to C
programmers.
© It supports features like aliasing, job control, and command history.
© Ithas built-in arithmetic expressions, which are useful in scripting.
+ Usage
© Less commonly used today but still found in some Unix environments.
© Preferred by some users who are familiar with C syntax.
4. TENEX C Shell (tesh)
+ Developer: Ken Greer
+ Location: /binvtesh
+ Features:
© tesh is an enhanced version of the C Shell (csh), with additional features Tike
command-line editing, filename completion, and spell checking.
© It provides a user-friendly command-line interface with better scripting support
compared to csh
+ Usage
© Popular among users who prefer C-like syntax with modern features.
© Used as an interactive login shell.
5. Korn Shell (ksh)
+ Developer: David Korn
+ Location: /bin/ksh
+ Features:
© Kom Shell combines features from both the Bourne Shell (sh) and C Shell (csh)..
It includes advanced scripting capabilities, including associative arrays, stringmanipulation, and floating-point arithmetic.
© Supports job control, command-line editing, and a history mechanism.
Usage:
© Used in both scripting and interactive use,
© Commonly found in commercial Unix systems like AIX and Solaris,
6. Z Shell (zsh)
Developer: Paul Falstad
Location: /bin/zsh
Features:
© zsh isa powerful and flexible shell that incorporates features from bash, ksh, and
tesh.
© Itoffers advanced features such as theme support, plugins, spelling correction, and
improved tab completion.
© Highly customizable and user-friendly, making it popular among developers and
power users.
© Preferred for its interactive features and customizability.
© Commonly used with frameworks like Oh My Zsh to enhance functionality.
The choice of shell depends on user preference, scripting requirements, and the specific
features needed. While ‘bash’ remains the most widely used and standard shell in Linux
distributions.
Shell Commands:
Linux shell commands are used to interact with the operating system by issuing
commands via a shell (command-line interface). Below is a list of commonly used shell
commands in Linux, along with their syntax and examples:
1. Is (List Directory Contents)
The “Is” command is used to list files and directories in the current directory.
Syntax:
Is [options] [directory]
Examples:
+ List files in the current directory:
Is
+ List all files, including hidden files (starting with
Is-a
+ List files with detailed information (permissions, owner, size, etc.):
Is
+ List files in a specific directory:
Is /ete
2. ed (Change Directory)
The “cd” command is used to change the current working directory.
Syntax:cd [directory]
Examples:
+ Change to the home directory:
cd~
+ Change to a specific directory:
cd /var/log
+ Move up one directory level:
ed.
3. pwd (Print Working Directory)
The “pwd” command displays the current working directory.
Syntax:
pwd
Exampl
+ Display the current directory:
pwd
4, mkdir (Make Directory)
The mkdir command is used to create new directories.
Syntax:
mkdir [options] directory_name
Examples:
+ Create a new directory named myfolder:
mkdir myfolder
+ Create a directory with parent directories
mkdir -p /path/to/myfolder
5. rmdir (Remove Directory)
The “rmdir” command removes empty directories.
Syntax:
rmdir [options] directory_name
Examples:
+ Remove an empty directory named myfolder:
rmdir myfolder
6. rm (Remove Files or Directories)
The “rm” command removes files or directories.
Syntax:
rm [options] file_name
Examples:
+ Remove a file named file.txt:
rm file.txt+ Remove a directory and its contents recursively:
1m -r myfolder
+ Forcefully remove a file (without prompting):
rm -f file.txt
7. ep (Copy Files or Directories)
The “cp” command copies files and directories.
Syntax:
cp [options] source destination
Examples:
+ Copy a file to a new location:
cp file.txt /home/user/backup/
+ Copy a directory and its contents:
cp -r myfolder /home/user/backup/
8. mv (Move or Rename Files or Directories)
The “my” command moves or renames files and directories.
Syntax:
my [options] source destination
Examples:
+ Rename a file:
my oldname.txt newname.txt
+ Move a file to a different directory:
my file.txt /home/user/backup/
9, cat (Concatenate and Display File Content)
The “cat” command displays the content of a file or coneatenates files.
Syntax:
cat [options] file_name
Examples:
+ Display the contents of a file:
cat file.txt
+ Coneatenate two files and display the result:
cat file txt file2.txt
10. touch (Create or Update File Timestamps)
The “touch” command creates an empty file or updates the timestamp of an
existing file.
Syntax:
touch [options] file_name
Examples:
+ Create an empty file:touch newfile.txt
+ Update the timestamp of an existing file:
touch existingfile.txt
11. chmod (Change File Permissions)
The “chmod” command changes the permissions of a file or directory.
Syntax:
chmod [options] mode file_name
Examples:
+ Make a file executable:
chmod +x scriptsh
+ Change file permissions to read and write for the owner, and read-only for others:
chmod 644 file.txt
12. chown (Change File Owner and Group)
The “chown” command changes the owner and group of a file or directory.
Syntax:
chown [options] owner{:group] file_name
Examples:
+ Change the owner of a file to user:
chown user file.txt
+ Change the owner and group of a file:
chown user:group file.txt
13. find (Search for Files)
The find command searches for files and directories in a directory hierarchy.
Syntax:
find [path] [options] [expression]
Examples:
+ Find all .txt files in the current directory:
find . -name "*.txt"
+ Find files larger than IMB:
find / -size +1M
14. grep (Search for Patterns in Files)
The grep command searches for a specified pattern in files.
Syntax:
grep [options] pattern [file...]
Examples:
+ Search for the word "example" in a file:
grep "example" file.txt+ Search recursively for a pattern in all files within a directory:
grep -r "example" /path/to/directory
+ Display disk space usage:
Writing & Executing First Script
‘What is Shell Seripting?
In Linus, shells like bash and korn support programming construct which are saved as
scripts. These scripts become shell commands and hence many Linux commands are script.
A system administrator should have a little knowledge about scripting to understand how
their servers and applications are started, upgraded, maintained or removed and to understand how
a user environment is built
A shell script is a type of computer program developed to be executed by a Unix shell,
which is also known as a command-line interpreter. Several shell script dialects are treated as
scripting languages. Classic operations implemented by shell scripts contain printing text, program
execution, and file manipulation, A script configures the environment, executes the program, and
does necessary logging or clean-up is known as a wrapper.
Steps to write the shell seript in:
Step-1: Open the terminal. Go to the directory where you want to create your seript.
Step-2: Create a file with .sh extension.
Step-3: Write the script in the file using an editor.
Step-4: Make the script executable with command chmod +x .
Step-5: Run the script using /.
In the last step you have to mention the path of the script if your script is in other directory.
Executing Fi
t Script
1. First of all, create a simple script in any editor or with echo.
2. Then we'll make it executable with chmod +x command.
3. To find the script you have to type the script path for the shell
Beene
Breas
Breas
Seu
4, Look at the above snapshot, script echo Hello World is created with echo commandas hello_world.
5. Now command chmod +x hello_world is passed to make it executable.
6. We have given the command “./hello_world” to mention the hello_world path. And output
is displayed.
Shell Variables
A shell variable in Linux is a variable that is defined and used in a shell script or the
command-line interface. It holds a value that can be referenced and manipulated within the shell.
Shell variables are typically used to store data such as user input, command output, or
configuration settings, which can be reused throughout a script or session.
Shell variables can be either local (visible only within the current shell or script) or
environment variables (available to the shell and any child processes). They are often used to make
scripts more flexible and easier to maintain by allowing users to change values without modifying
the entire script
‘Types of Shell Variables
1, Local Variables: These are only available to the current shell. They are defined without
the export keyword.
2. Environment Variables: These are available to the current shell and any child processes.
They are defined using the export keyword,
Examples of Shell Variables
1. Local Shell Variable
Here's an example of a simple script that uses a local shell variable:
#U/bin/bash
# Define a local variable
greeting="Hello, World!"
# Print the value of the variable
echo $greeting
+ Inthis example, the variable greeting is defined and assigned the value "Hello, World!
+ The echo command is used to print the value of the greeting variable.
2. Environment Variable
Environment variables are set using the export command and are available to any child
processes. Here's how you might use one:
#Y/bin/bash
4# Define and export an environment variable
export PATH="/usr/local/bin:$PATH"# Print the value of the PATH variable
echo $PATH
+ Inthis example, the PATH variable is updated by prepending /usr/local/bin to its value
+ export makes this change available to any child processes.
+ The echo command prints the current value of the PATH variable.
Example Program Using Shell Variables
Here’s a simple script that uses shell variables to perform a basic arithmetic operation and
display the result:
#Y/bin/bash
# Define shell variables
num1=10
num2:
# Perform arithmetic operation and store the result in a variable
(num + num2))
# Print the result
echo "The sum of $num! and $num? is: $sum"
Explanation:
+ numt and num? are shell variables storing integer values,
+ sum is another shell variable that stores the result of the arithmetic operation.
+ The echo command outputs the result.