Linux (Chapter 2)
Linux (Chapter 2)
SHELLS
The computer understands the language of 0’s and 1’s called binary
language. In the early days of computing, instructions are provided
using binary language, which is difficult for all of us, to read and write.
So the in Operating system there is special program called Shell that
acts as an interface between user and kernel.
Linux has a large number of commands. A Linux command is a
program written to perform a certain specific action. All such
programs have a name.
For example, the program that is used to print today’s date in a specific
manner has the name date.
All Linux commands are written using lower case letters and they are
case sensitive.
For example date, cat, cp, ls, pwd, who, wc, and so on.
Understanding Shells
1. No Desktop - If your Linux system has no GUI (or one that isn’t
working at the moment), you log in from a text-based prompt
and immediately begin working from the shell.
2. With Desktop - With the desktop GUI running, you can open a
Terminal window (right-click on the desktop, and then click
Open Terminal) to start a shell. You can begin typing commands
into the Terminal window.
If you are using a shell interface, the first thing you see is the shell
prompt.
As soon as the system is booted successfully, the shell prompts a
command line prompt.
The default prompt for a normal user is simply a dollar sign: $
The default prompt for the root user is a pound sign (also called a hash
mark):#
If you use a shell other than the default bash shell in Fedora, in some
cases you may see a percent sign (%) as the user prompt instead of the
pound sign.
For most Linux systems, the $ or # prompts are preceded by your user
name, system name, and current directory name. So, for example, a
login prompt for the user named sanjay on a computer named
localhost with /home/user1 as the current directory would appear as:
When you see a tilde (~) character as the current directory (instead of
tmp as shown in the preceding code), it indicates that your home
directory is the current directory.
In the examples that follow, the $ or # symbols indicate a prompt.
The prompt is followed by the command that you type and then by
Enter. The lines that follow show the output that result from the
command.
knows when you logged in, how long you have been idle, and where
you logged in from.
To find out information about your identity, use the id command as
follows:
$id
context=user_u:system_r:unconfined_t
This shows that the user name is nitish, which is represented by the
numeric user ID (uid) 501. Here, the primary group for nitish is called
sales, which has a group ID (gid) of 105. Nitish also belongs to other
groups called adm (gid 4) and lp (gid 7). These names and numbers
represent the permissions that nitish has to access computer
resources.
To exit the shell when you are done, do one of the following:
$exit
Types of Shell:
The C Shell
Denoted as csh
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.
In C shell:
Command full-path name is /bin/csh,
Non-root user default prompt is hostname %,
Root user default prompt is hostname #.
pwd Command
pwd stands for Print Working Directory. 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).
$PWD is an environment variable which stores the path of the current
directory.
cd Command
$ cd /
$ cd dir_1/dir_2/dir_3
$ cd ~
$ cd ..
Date Command
date command is used to display the system date and time.
date command is also used to set date and time of the system.
By default the date command displays the date in the time zone on
which unix/linux operating system is configured.
Syntax:
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
1. date (no option) : With no options, the date command displays the
current date and time, including the abbreviated day name,
abbreviated month name, day of the month, the time separated by
colons, the time zone name, and the year.
Command:
$date
Output:
Tue Oct 10 22:55:01 PDT 2017
Command:
$date -u
Output :
Wed Oct 11 06:11:31 UTC 2017
Syntax:
$date --date=" string "
Command:
$date --date="2/02/2010"
$date --date="Feb 2 2010"
Output:
Tue Feb 2 00:00:00 PST 2010
Tue Feb 2 00:00:00 PST 2010
Command:
$date --date="2 year ago"
Output:
Sat Oct 10 23:42:15 PDT 2015
Command:
$date --date="yesterday"
Output:
Mon Oct 9 23:48:00 PDT 2017
Command:
$date --date="next tue"
Output:
Tue Oct 17 00:00:00 PDT 2017
ls Command
The ls command is used to list files or directories in Linux and other
Unix-based operating systems.
Just like you navigate in your File Explorer or Finder with a GUI,
the ls command allows you to list all files or directories in the current
directory by default, and further interact with them via the command
line.
If you have a lot of files, this can take a very long time to complete as every
single file in each directory will be printed out. You can instead specify a
directory to run this command in, like so: ls Downloads –R.
cp command
cp stands for copy.
This command is used to copy files or group of files or directory.
It creates an exact image of a file on a disk with different file name.
cp command require at least two filenames in its arguments.
Syntax:
cp [OPTION] Source Destination
cp [OPTION] Source Directory
cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory
The first and second syntax is used to copy Source file to the
Destination file or Directory.
The third syntax is used to copy multiple Sources(files) to Directory.
cp Src_file Dest_file
Suppose there is a directory named site having a text
file a.txt.
Example:
$ ls
a.txt
$ cp a.txt b.txt
$ ls
a.txt b.txt
2. One or more arguments :
If the command has one or more arguments, specifying file
names and following those arguments, an argument
specifying directory name then this command copies each
source file to the destination directory with the same
name, created if not existed but if already existed then it
will be overwritten, so be careful.
Syntax:
cp Src_file1 Src_file2 Src_file3 Dest_directory
Suppose there is a directory named site having a text
file a.txt, b.txt and a directory name new in which we are
going to copy all files.
Example:
$ ls
a.txt b.txt new
$ ls new
a.txt b.txt
$ cat a.txt
GFG
$ cat b.txt
Site
1.-i(interactive): i stands for Interactive copying.
With this option system first warns the user before
overwriting the destination file. cp prompts for a response, if
you press y then it overwrites the file and with any other
option leave it uncopied.
$ cp -i a.txt b.txt
cp: overwrite 'b.txt'? y
$ cat b.txt
GFG
$ cp -b a.txt b.txt
$ ls
a.txt b.txt b.txt~
$ ls gfg/
a.txt b.txt b.txt~ Folder1 Folder2
4.Copying using * wildcard: The star wildcard represents anything i.e. all
files and directories.
Suppose we have many text document in a directory and wants to copy
it into another directory, it takes lots of time if we copy files 1 by 1 or
the command becomes too long if specify all these file names as the
argument, but by using * wildcard it becomes simple.
Initially, Folder1 is empty
$ ls
a.txt b.txt c.txt d.txt e.txt Folder1
$ cp *.txt Folder1
$ ls Folder1
a.txt b.txt c.txt d.txt e.txt
mkdir command
mkdir command in Linux allows the user to create directories (also
referred to as folders in some operating systems ).
This command can create multiple directories at once as well as set the
permissions for the directories. It is important to note that the user
executing this command must have enough permissions to create a
directory in the parent directory, or he/she may receive a ‘permission
denied’ error.
Syntax:
mkdir [options...] [directories ...]
If the first and second directories do not exist, due to the -p option,
mkdir will create these directories for us. If we do not specify the -p
option, and request the creation of directories, where parent
directory doesn’t exist, we will get the following output –
5. -m: 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 a=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 ‘a=r’ to only allow all the users to read
from the directories and so on.
Output:
touch command
It is used to create a file without any content.
The file created using touch command is empty. This command can be
used when the user doesn’t have data to store at the time of file
creation.
o Syntax:
o touch file_name
The file which is created can be viewed by ls command and to get more
details about the file you can use long listing command ls -l command
. Here file with name ‘File1‘ is created using touch command.
Syntax:
touch File1_name File2_name File3_name
Multiple files with name Doc1, Doc2, Doc3 are created at the same time
using touch command here.
rm command
rm 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.
Syntax:
rm [OPTION]... FILE...
Let us consider 5 files having name a.txt, b.txt and so on till e.txt.
$ ls
a.txt b.txt c.txt d.txt e.txt
Removing one file at a time
$ rm a.txt
$ ls
b.txt c.txt d.txt e.txt
$ ls
d.txt e.txt
Note: No output is produced by rm, since it typically only generates
messages in the case of an error.
Options with Example:
1. -i (Interactive Deletion): Like in cp, 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
rm: remove regular empty file 'd.txt'? y
$ ls
e.txt
$ ls
A
$ cd A
$ ls
B C
$ ls B
a.txt b.txt
$ ls C
c.txt d.txt
$ rm -r *
$ ls
rmdir command
rmdir command is used to remove empty directories from the
filesystem in Linux. The rmdir command removes each and every
directory specified in the command line only if these directories are
empty. So if the specified directory has some directories or files in it
then this cannot be removed by the rmdir command.
Syntax:
Options:
2. rmdir -v, --verbose: This option displays verbose information for every
directory being processed.
Example 1: This will first remove the child directory and then remove the
parent directory.
rmdir -p mydir/mydir1
Example 2: Remove the directories mydir1, mydir2, and mydir3, if they are
empty. If any of these directories are not empty, then an error message will be
printed for that directory, and the other directories will be removed.
mv command
mv stands for move. mv is used to move one or more files or
directories from one place to another in a file system like UNIX.
It has two distinct functions:
(i) It renames a file or folder.
(ii) It moves a group of files to a different directory.
$ mv a.txt geek.txt
$ ls
b.txt c.txt d.txt geek.txt
If the destination file exist, then it will be overwrite and the source
file will be deleted. By default, mv doesn’t prompt for overwriting the
existing file, So be careful.
Let’s try to understand with an example,
moving geeks.txt to b.txt(exist):
$ ls
b.txt c.txt d.txt geek.txt
$ cat geek.txt
India
$ cat b.txt
geeksforgeeks
$ mv geek.txt b.txt
$ ls
b.txt c.txt d.txt
$ cat b.txt
India
1. -i (Interactive): Like in cp, the -i option makes the command ask the
user for confirmation before moving a file that would overwrite an
existing file, you have to press y for confirm moving, any other key
leaves the file as it is. This option doesn’t work if the file doesn’t exist,
it simply rename it or move it to new location.
$ ls
b.txt c.txt d.txt geek.txt
$ cat geek.txt
India
$ cat b.txt
geeksforgeeks
$ mv -i geek.txt b.txt
mv: overwrite 'b.txt'? y
$ ls
b.txt c.txt d.txt
$ cat b.txt
India
$ ls -l b.txt
-r--r--r--+ 1 User User 13 Jan 9 13:37 b.txt
$ mv geek.txt b.txt
mv: replace 'b.txt', overriding mode 0444 (r--r--r--)? n
$ ls
b.txt c.txt d.txt geek.txt
$ mv -f geek.txt b.txt
$ ls
b.txt c.txt d.txt
$ cat b.txt
India
$ mv -n geek.txt b.txt
$ ls
b.txt c.txt d.txt geek.txt
$ cat b.txt
Geeksforgeeks
$ mv -b geek.txt b.txt
$ ls
b.txt b.txt~ c.txt d.txt
cat command
cat(concatenate) command is very frequently used in Linux. It reads
data from the file and gives their content as output. It helps us to
create, view, concatenate files. So let us see some frequently used cat
commands.
Command:
$cat filename
Output :
Command:
$cat file1 file2
Output :
Command:
$cat -n filename
Output :
example:-cat-n geeks.txt
1)This is geeks
4) Create a file
Command:
$ cat > newfile
Output :
Command:
$cat [filename-whose-contents-is-to-be-copied] > [destination-
filename]
Output :
6) Cat command can append the contents of one file to the end of
another file.
Command:
$cat file1 >> file2
Output :
Will append the contents of one file to the end of another file
Command:
$tac filename
Output :
Command:
$cat -E "filename"
Output :
9) Cat command if the file has a lot of content and can’t fit in the
terminal.
Command:
$cat "filename" | more
Output :
Will show that much content, which could fit in terminal and will
ask to show more.
Command:
$cat "filename1" "filename2" "filename3" > "merged_filename"
Output :
Will merge the contents of file in respective order and will insert
that content in "merged_filename".
11) Cat command to display the content of all text files in the folder.
Command:
$cat *.txt
Output :
Will show the content of all text files present in the folder.
Command :
$cat >> geeks.txt
Output:
Will append the text "The newly added text." to the end of the
file.
wc command
wc stands for word count. As the name implies, it is mainly used for
counting purpose.
It is used to find out number of lines, word count, byte and
characters count in the files specified in the file arguments.
By default it displays the four-columnar output.
First column shows number of lines present in a file specified, second
column shows number of words present in the file, third column shows
number of characters present in file and fourth column itself is the file
name which are given as argument.
Syntax:
wc [OPTION]... [FILE]...
Let us consider two files having
name state.txt and capital.txt containing 5 names of the Indian states
and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
$ cat capital.txt
Hyderabad
Itanagar
Dispur
Patna
Raipur
Passing only one file name in the argument.
$ wc state.txt
5 7 63 state.txt
OR
$ wc capital.txt
5 5 45 capital.txt
Passing more than one file name in the argument.
$ wc state.txt capital.txt
5 7 63 state.txt
5 5 45 capital.txt
10 12 108 total
3. -c: This option displays count of bytes present in a file. With this
option it display two-columnar output, 1st column shows number of
bytes present in a file and 2nd is the file name.
With one file name
$ wc -c state.txt
63 state.txt
5. -L: The ‘wc’ command allow an argument -L, it can be used to print
out the length of longest (number of characters) line in a file.
So, we have the longest character line Arunachal Pradesh in a
file state.txt and Hyderabad in the file capital.txt.
But with this option if more than one file name is specified then
the last row i.e. the extra row, doesn’t display total but it display
Applications of wc Command
1. To count all files and folders present in the directory:
As we all know ls command in UNIX is used to display all the files
and folders present in the directory, when it is piped
with wc command with -l option it displays the count of all files
and folders present in the current directory.
$ ls gfg
a.txt
b.txt
c.txt
d.txt
e.txt
geeksforgeeks
India
$ ls gfg | wc -l
7
grep command
The grep filter searches a file for a particular pattern of characters, and
displays all lines that contain that pattern.
The pattern that is searched in the file is referred to as the regular
expression (grep stands for global search for regular expression and
print out).
Syntax:
grep [options] pattern [files]
Options Description:
1. -c : This prints only a count of the lines that match a pattern
2. -h : Display the matched lines, but do not display the filenames.
3. -i : Ignores, case for matching
4. -l : Displays list of a filenames only.
5. -n : Display the matched lines and their line numbers.
6. -v : This prints out all the lines that do not matches the pattern
7. -e exp : Specifies expression with this option. Can use multiple times.
8. -f file : Takes patterns from file, one per line.
9. -w : Match whole word
10. -o : Print only the matched parts of a matching line, with each such
part on a separate output line.
13. -C n : Prints searched line and n lines after before the result.
Sample Commands
Consider the below file as an input.
1. Case insensitive search : The -i option enables to search for a string case
insensitively in the given file. It matches the words like “UNIX”, “Unix”,
“unix”.
3. Display the file names that matches the pattern : We can just display
the files that contains the given string/pattern.
$grep -l "unix" *
or
$grep -l "unix" f1.txt f2.txt f3.xt f4.txt
Output:
geekfile.txt
4. Checking for the whole words in a file : By default, grep matches the
given string/pattern even if it is found as a substring in a file. The -w option
to grep makes it match only the whole words.
unix
unix
unix
unix
unix
unix
6. Show line number while displaying the output using grep -n : To show
the line number of file with the line matched.
7. Inverting the pattern match : You can display the lines that are not
matched with the specified search string pattern using the -v option.
8. Matching the lines that start with a string : The ^ regular expression
pattern specifies the start of a line. This can be used in grep to match the
lines which start with the given string or pattern.
9. Matching the lines that end with a string : The $ regular expression
pattern specifies the end of a line. This can be used in grep to match the lines
which end with the given string or pattern.
11. Print n specific lines from a file: -A prints the searched line and n lines
after the result, -B prints the searched line and n lines before the result, and -
C prints the searched line and n lines after and before the result.
Syntax:
$grep -A[NumberOfLines(n)] [search] [file]
(Prints the searched line along with the next n lines (here n = 1 (A1).)
(Will print each and every occurrence of the found line, separating each
output by --)
(Output pattern remains the same for -B and -C respectively)
Unix linux which one you choose.
--
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a
powerful.
Unix linux which one you choose.
--
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a
powerful.
stat command
The stat is a command which gives information about the file and
filesystem.
Stat command gives information such as the size of the file, access
permissions and the user ID and group ID, birth time access time of the
file.
Stat command has another feature, by which it can also provide the file
system information.
Syntax :
stat --options filenames
Example:
stat a3.docx
Output:
File: The name of the provided file. If the provided file is a symlink, then
the name will be different.
Size: The size of a given file in Bytes.
Blocks: Total number of allocated blocks to the file to store on the hard
disk.
IO Block: The size of every allocated block in bytes.
File type: The file may be of the following types: Regular files, special
files, directories, or symbolic links.
Device: Device number in hexadecimal format.
Inode: Inode number of the file.
Links: Number of hard links of the file.
Access: Access permissions in the numeric and symbolic methods.
Context: The field stores SELinux security context.
Access: The last time at which the file was accessed.
Modify: The last time at which file was modified.
Change: The last time the at which file’s attribute or content was
changed.
Birth: The time at which the file was created.
man command
man command in Linux is used to display the user manual of any
command that we can run on the terminal.
It provides a detailed view of the command which includes NAME,
SYNOPSIS, DESCRIPTION, OPTIONS, EXIT STATUS, RETURN VALUES,
ERRORS, FILES, VERSIONS, EXAMPLES, AUTHORS and SEE ALSO.
Syntax :
$man [OPTION]... [COMMAND NAME]...
Example:
$ man printf
Output:
In this example, manual pages of the command ‘printf‘ are simply returned.
clear command
clear is a standard Unix computer operating system command that is
used to clear the terminal screen.
This command first looks for a terminal type in the environment and
after that, it figures out the terminfo database for how to clear the
screen. And this command will ignore any command-line parameters
that may be present.
Also, the clear command doesn’t take any argument and it is almost
similar to cls command on a number of other Operating Systems.
Syntax:
$clear
Example:
history Command
history command is used to view the previously executed command.
This feature was not available in the Bourne shell.
Bash and Korn support this feature in which every command executed
is treated as the event and is associated with an event number using
which they can be recalled and changed if required.
These commands are saved in a history file. In Bash
shell history command shows the whole list of the command.
Syntax:
$ history
chmod Command
1. Linux File Ownership
Every file and directory on your Unix/Linux system is assigned 3 types of the
owner, as given below.
User
A user is the owner of the file. By default, the person who created a file
becomes its owner. Hence, a user is also sometimes called an owner.
Group
Other
Hence, when you set the permission for others, it is also referred to as
set permissions for the world.
Now, the big question arises how does Linux distinguish between
these three user types so that a user ‘A’ cannot affect a file which
contains some other user ‘B’s’ vital information/data. It is like you do
not want your colleague, who works on your Linux computer, to view
your images.
This is where Permissions are set in, and they define user behavior.
Every file and directory in your UNIX/Linux system has the following 3
permissions defined for all the 3 owners discussed above.
Read: This permission give you the authority to open and read a file.
Read permission on a directory gives you the ability to list its
content.
Write: The write permission gives you the authority to modify the
contents of a file.
But you will not be able to rename, move or remove the file from the
directory.
File
Permissions in Linux/Unix
ls – l on terminal gives
ls - l
r = read permission
w = write permission
x = execute permission
– = no permission
The first part of the code is ‘rw-‘. This suggests that the owner ‘Home’
can:
The third part is for the world which means any user. It says ‘r–‘. This
means the user can only:
Say you do not want your colleague to see your personal images. This
can be achieved by changing file permissions.
We can use the ‘chmod’ command which stands for ‘change mode’.
Using the command, we can set permissions (read, write, execute) on a
file/directory for the owner, group and the world.
Syntax:
1. Absolute mode
2. Symbolic mode
The table below gives numbers for all for permissions types.
0 No Permission —
1 Execute –x
2 Write -w-
4 Read r–
In the Absolute mode, you change permissions for all 3 owners. In the
symbolic mode, you can modify permissions of a specific owner.
It makes use of mathematical symbols to modify the Unix file
permissions.
Operator Description
+ Adds a permission to a file or directory
– Removes the permission
= Sets the permission and overrides the permissions set
earlier.
User Denotations
u user/owner
g group
o other
a all