You are on page 1of 81

Linux

command

1
Index

Sr. No. Contents Page No.

1. Working with Directories

1.1) pwd command 7


1.2) cd command 7
 cd ~ command
 cd .. command
 cd – command
 cd / command
1.3) ls command 9
 ls –a command
 ls –l command
 ls –lh command
 ls –lhs command
 ls –r command
 ls –R command
 ls –lX command
 ls –lt command
 ls ~ command
 ls ../ command
1.4) mkdir command 13
 To make multiple directories
 Mkdir –p command
1.5) rmdir command 14

2. Working with Files

2.1) file command 15


2.2) touch command 15
 touch –r command
 touch –t command
2.3) rm command 16
 rm –i command
 rm –rf command
2.4) cp command 17
 cp –r command
 cp –i command
2.5) mv command 18
 mv –i command

2
3. Working with file Contents

3.1) head command 19


 Head –n command
 Head –c command
3.2) tail command 20
3.3) cat command 20
 Create text file
 To append the content of a file
 Copy content to other file
 cat –n command
 cat –b command
 cat –e command
 Marker command
3.4) tac command
23
3.5) more command 23
3.6) less command
24

4. Working with Linux admin command

4.1) uptime command 25


4.2) service command 25
 stop command
 start command
 restart command
 status command
4.3) Terminating command 26
 kill command
 kill –l command
 killall command
4.4) pmap command 28
4.5) wget command 28
 Save with different file name
 Completing partially downloaded file
 Download multiple file 29
4.6) free command 30
4.7) top command
 Keeping top command running in background
 Sorting top output
 Killing a task without existing from top
 Renice a task
 Display process of selected user
 Updating top output
 Changing colors
 Quitting after certain iteration

3
4.8) last command 36
 Display full login and logout time
 Display specific username
 Display reboot information
 Display specific pts
4.9) ps command 39
 List running process in full
 List all running process
 List process with specific username
 List process with specific command
 Listing process in hierarchy
 Show root running process 43
4.10) Shutdown command
 Shutting down system
 Rebooting the system
 Power-off or halt-off the system
 Power-off the system
 Printing a message during shutdown
 Halt-off the system
 Cancel shutdown
 Sending warning and disabling logins
4.12) env command 46
4.12) du command 47
4.13) shred command 47
 To delete file

5. Linux user’s management

5.1) whoami command 48


5.2) who command 48
5.3) who am i command 48
5.4) w command 49
5.5) id command 49
5.6) su command 49
 su to root
 su as root
 su -$username command
 su – command
5.7) useradd command 51
5.8) userdel command 51
5.9) usermod command 52
5.10) passwd command 52
 Encryption with passwd
 Chage command
 Disabling a password
 Unlocking a password

4
5.11) Group command 55
 groupadd command
 groups command
 usermod command
 groupmod command
 groupdel command

6. Linux File Security

6.1) Linux file Ownership 57


6.2) Listing User Account 57
6.3) Chgrp command 58
6.4) Chown command 58
6.5) Setting Permission with chmod 59
 To add permissions to a group
 To remove permissions from a group
 To add permission to all the groups together
 To set explicit permission
 mkdir –m

7. Linux Filter Command

7.1) cat command 61


7.2) Cut command 61
 Hyphen as delimiter
 Space as delimiter
7.3) grep command 63
 grep with pipe
 grep without pipe
 grep options
7.4) comm. command 65
 To display single column
7.5) tr command 66
 Change case
 Remove new line
 tr options
69
7.6) uniq command
 Uniq –c command 69
7.7) wc command 70
7.8) sort command
 To sort column
 Numeric sorting 72
7.9) gzip command
 Compressing multiple files together
 gzip –l command
 To compress a directory

5
8. Linux Networking command

8.1) ifconfig command 74


 Assigning IP address and Gateway
 Enable and Disable specific interface
 Setting MTU size
8.2) ip command 75
8.3) ping command 75
 Ping using DNS
 Ping using IP address
 Ping to limit the packet
8.4) host command 76

9. Extra Command

9.1) find command 77


 Finding by name
 Finding by type
9.2) locate command 78
9.3) date command 78
 date format
9.4) cal command 79
 Display past or future month
9.5) sleep command 79
9.6) zcat command 80
9.7) df command 80

10. References 81

6
1) Working with Directories

1.1) pwd command:


pwd (print working directory) command displays your location currently you are working on. It will
give the whole path starting from the root ending to the directory.

1.2) cd command:
The "cd" stands for 'change directory' and this command is used to change the current directory i.e.;
the directory in which the user is currently working.

 cd ~ command (Brings you to your home directory):


The cd is also a shortcut to get back into your home directory. Just typing cd without a target directory,
will put you in your home directory. Typing cd ~ has the same effect.

7
 cd .. command (Brings you to the parent directory of current directory)
To go to the parent directory (the one just above your current directory in the directory tree)

 cd – command (Brings you to your previous directory of the current directory)


Another useful shortcut with cd is to just type cd - to go to the previous directory.

 cd / command (It takes you to the entire system's root directory)


Go to the root directory.

8
1.3) ls command:
The ls are the list command in Linux. It will show the full list or content of your directory.

 ls –a command
In Linux, hidden files start with .(dot) symbol and they are not visible in the regular directory. The (ls -a)
command will enlist the whole list of the current directory including the hidden files.

 ls –l command
Many times you will be using options with ls to display the contents of the directory in different formats
or to display different parts of the directory. Typing just ls gives you a list of files in the directory. Typing
ls -l gives the list in a long list format

9
 ls –lh command
This command will show you the file sizes in human readable format. Size of the file is very difficult to
read when displayed in terms of byte. The (ls -lh) command will give you the data in terms of Mb, Gb,
Tb, etc.

 ls –lhS command
If you want to display your files in descending order (highest at the top) according to their size, then you
can use (ls -lhS) command.

 ls –r command
It is used to print the list in reverse order.

10
 ls –R command
It will display the content of the sub-directories also.

 ls –lX command
It will group the files with same extensions together in the list.

11
 ls –lt command
It will sort the list by displaying recently modified filed at top.

 ls ~ command
It gives the contents of home directory.

 ls ../ command
It gives the contents of parent directory.

12
1.4) mkdir command:
The mkdir stands for 'make directory'. With the help of mkdir command, you can create a new
directory wherever you want in your system.

If you will not provide a path then by default your file will be created in your current directory only.
If you want to create your directory somewhere else, then provide the path of your destination
directory and your file will be created there.

 To make multiple directories

Syntax: mkdir <dirname1> <dirname2> <dirname3> ...

 mkdir –p command
Using mkdir –p command you can also create multiple directories simultaneously.

13
1.5) rmdir command:
This command is used to remove a directory. But will not be able to remove a directory including a
sub-directory. It means, a directory has to be empty to be removed.

14
2) Working with Files

2.1) file command:


The file utility determines the file type. Linux does not use extensions to determine the file type. The
command line does not care whether a file ends in .txt or .pdf. As a system administrator, you should
use the file command to determine the file type. Here are some examples on a typical Linux system.

2.2) touch command:


The touch command is a way to create empty files. You can update the modification and access time
of each file with the help of touch command.

 touch –r command
To update time of one file with reference to the other file.

15
 touch –t command
To create a file by specifying the time.

2.3) rm command:
The 'rm' means remove. This command is used to remove a file. The command line doesn't have a
recycle bin or trash unlike other GUI's to recover the files. Hence, be very much careful while using
this command. Once you have deleted a file, it is removed permanently.

 rm –i command
Remove a file interactively. To prevent yourself from accidentally removing a file, you can type rm -i.

16
 rm –rf command
Remove a directory forcefully. By default, rm -r will not remove non-empty directories. The rm -rf
statement is famous because it will erase anything (providing that you have the permissions to do so).
When you are logged on as root, be very careful with rm -rf (the f means force and the r means recursive)
since being root implies that permissions don't apply to you. You can literally erase your entire file
system by accident.

2.4) cp command:
'cp' means copy. 'cp' command is used to copy a file or a directory.

 cp –r command
To copy a directory along with its sub directories. (The -r option forces recursive copying of all files in all
subdirectories)

17
 cp –i command
To prevent cp from overwriting existing files, use the -i (for interactive) option.

2.5) mv command:
Linux mv command is used to move existing file or directory from one location to another. It is also
used to rename a file or directory.
If you want to rename a single directory or file then 'mv' option will be better to use.

 mv –i command
mv -i will ask permission to overwrite an existing file.

18
3) Working with File Contents

3.1) head command:


The 'head' command displays the starting content of a file. By default, it displays starting 10 lines of
any file.

 head –n command
The 'head -n' option displays specified number of lines.

 head –c command
The 'head -c' command display the first n bytes of file

19
3.2) tail command:
The 'tail' command displays the last lines of a file. Its main purpose is to read the error message.
By default, it will also display the last ten lines of a file.

3.3) cat command:


The 'cat' command can be used to display the content of a file.

 Create text file


You can use cat to create flat text files. Then type one or more lines, finishing each line with the
enter key. After the last line, type and hold the Control (Ctrl) key and press d. The Ctrl d key
combination will send an EOF (End of File) to the running process ending the cat command.

20
 To Append the content of a file
The ‘cat’ command with double greater than sign (>>) append something in your already existing file.

 Copy content to other file


To copy content from older to new file.

 cat –n command
The 'cat -n' option displays line numbers in front of each line in a file.

21
 cat –b command
The 'cat -b' option add line number to non-blank lines.

 cat –e command
The 'cat-e' option displays '$' sign at the end of every line.

 Marker command
The 'cat << EOF ' option displays end marker at the end of a file. This is called here directive and file
content will be saved at the given end marker.
File can be also saved with the help of 'ctrl + d ' keys. It works same as end marker.
Note: Any word other than 'EOF' can be used for the end marker.

22
3.4) tac command:
The 'tac' command is the reverse of the 'cat' command. It is also known as 'cat' backwards. It will
display the file content in reverse order.

3.5) more command:


As 'cat' command displays the file content. Same way 'more' command also displays the content of a
file. Only difference is that, in case of larger files, 'cat' command output will scroll off your screen
while 'more' command displays output one screenful at a time.
Following keys are used in 'more' command to scroll the page:
 Enter key: To scroll down page line by line.
 Space bar: To go to next page.
 b key: To go to the backward page.
 / key: Lets you search the string.

23
3.6) less command:
The 'less' command is same as 'more' command but include some more features. It automatically
adjust with the width and height of the terminal window, while 'more' command cuts the content as
the width of the terminal window get shorter.

Example: less fileA.txt

24
4) Working with Linux Admin Command

4.1) uptime command:


The uptime command tells us how long a system has been running.

From the left, it shows,


 current system time
 duration for which system has been running (system is running since 18 minutes)
 number of users logged in (2 users are logged in)
 System load average CPU load for past 1, 5 and 15 minutes.

Here, system load averages are the processes which are either in runnable or in uninterruptable state.

A runnable process may be either a running one using CPU or waiting to use CPU. An
uninterruptable process is waiting for some I/O access.

4.2) service command:


The service command starts, stop and restart a daemon or services by calling the script. Usually all
scripts are stored in /etc/init.d directory.
It runs a script in as predictable environment as possible.

Syntax: service script_name command


Here, command can be anyone from start, stop, restart, status.
 stop command
To stop a service use the following syntax,
Syntax: service script_name stop

 start command
To start a service use the following syntax,
Syntax: service script_name start

 restart command
To restart a service use the following syntax,
Syntax: service script_name restart

25
 status command
To get current status of a service use the following syntax,
Syntax: service script_name status

4.3) Terminating command:


There are four ways to kill or terminate a process. These commands allow you to run the system
uninterruptedly after terminating a process without rebooting the system. These commands can be
internal or external.

To use terminating commands you need to know different PIDs. PID for a process can be find out
with the following command,

Syntax: ps -A

 kill command
The most common command to terminate a process is kill command. You need to know the PID of the
process you want to terminate.

kill command sends signal to the specified process. For sending signal either signal name or signal
number can be used.

Syntax: kill -SIGNAL PID

26
 kill -l command
To see a list of signal names in your system.

 killall command
The killall command needs the process name instead of PID. It kills all the processes with the specified
name in the system.
Syntax: killall -<signal name or option> <name>

Command killall is case sensitive, to make it non case sensitive, use killall –I

27
4.4) pmap command:
The command pmap reports memory map of one process or multiple processes. It displays
information about memory usage and address space of a process. To check pmap of a process we
need PID of the process.

Syntax: pmap PID


Example: pmap 2390

4.5) wget command:


Command wget stands for web get. The wget is a free non-interactive file downloader command.
Non-interactive means it can work in background when user is not logged in. This allows user to get
disconnected with the system while wget finish its work.

The main feature of wget is its robustness and recursiveness. Due to its robustness, it works even in
slow internet connection. It automatically starts downloading the file from where it was left in case of
network failure. Due to its recursiveness, it keeps trying until the file is retrieved completely.

In some systems wget may not be installed. To install wget use the following command,
sudo apt-get install wget

Single file can be downloaded with following syntax. By default this file is saved in the current
directory.

Syntax: wget <URL>


Example: wget https://www.google.com/doodles/gerardus-mercators-503rd-birthday

28
 Save with different file name:

By default, downloaded file will be saved with the last name mentioned in the URL. To save file with a
different name option O can be used.

Syntax: wget -O <fileName><URL>

 Completing partially downloaded file


Suppose you are downloading a very large file, after 80% downloading your internet connection is
interrupted due to some reason and file is not completely downloaded. In this case, instead of starting a
whole download again, just restart downloading from where it stopped with the help of c option.

Syntax: wget -c <URL>

 Download multiple files


To download multiple files together, store all the urls in a single file.
Now, we'll download all these three files together using option i.

Syntax: wget -i <fileName>


Example: wget -i urls.txt

4.6) free command:


The free command gives information about used and unused memory usage and swap memory of a
system. By default, it displays memory in kb (kilobytes).
Memory mainly consists of RAM (random access memory) and swap memory.
Swap memory is a part of hard disk drive that acts like a virtual RAM.

29
4.7) top command:
The top command displays all the running process within the environment of your system. It helps in
monitoring system usage and performances. It is mainly used to detect load on the server by system
administrators.

 Line1
 Time
 how long system is running
 how many users are logged in
 and load average

 Line2
 Total number of tasks
 number of running tasks
 number of sleeping tasks
 number of stopped tasks
 and number of zombie tasks

 Line3
 It shows CPU usage in percentage for
 users
 system
 low priority processes
 idle processes
 io wait
 hardware interrupts
 software interrupts
 steal time

30
 Line4
 It shows memory usage in kilobytes for
 total memory
 used memory
 free memory
 buffered memory

 Line5
 It shows swap memory usage in kilobytes for
 total memory
 used memory
 free memory
 cached memory

 Table explanation
 process ID
 user
 priority
 nice user
 virtual memory
 resident memory
 shareable memory
 CPU used percentage
 memory used percentage
 time a process has run
 command

 Keeping top command running in background


You can keep top command running in the background continuously without typing top in terminal every
time. Use ctrl+z keys to get back your terminal.

Look at the above snapshot, after pressing ctrl+z keys top command has stopped and we got our terminal
back.

To bring back top command in terminal type fg in terminal.

31
 Sorting top output

By default, top command always displays output in the order of CPU usage.

Press M ? To display in order of memory usage.

Press R ? To display in reverse order.

32
 Killing a task without exiting from top
A task can be stopped without exiting from top command by pressing k key.

It will ask for task's PID number, if you'll have authority to kill that task, then task will be removed.
Otherwise, your command will fail.

Look at the above snapshot, after pressing k, we got a message asking for PID of task to be killed.

 Renice a task
Renice is done to change the scheduling order. By pressing r, you can change the priority of a process
without killing it. It will also ask for PID of the process.

Look at the above snapshot, after pressing r, we got a message asking for PID of task to be reniced.

33
 Display processes for selected user
In top command output you can display all the processes for a particular user only by two options. One
through command line and other without existing top.

Syntax: top -u <userName>


Example: top -u sssit

Look at the above snapshot, it displays all the processes only for user prashant.

When top command is running, press u, it will ask for username. Type the username and press enter.

Look at the above snapshot, after pressing u, it is asking for username.

34
 Updating top output
By default, top output is updated after every 3 seconds. When you want to update it in between 3 seconds
press space bar.

You can also change updating frequency by pressing d key while running top command.

 Changing colors
Colors can be changed by pressing z key and text can be made bold by pressing b key.

Look at the above snapshot, by pressing b all running processes are highlighted in white.

To change color press z (small z) key.

Look at the above snapshot, our output is colored after pressing z.

Now, if you want to change the colors for different areas, press Z (capital Z). it will take you to the menu
where you can select different colors for different target.

35
Suppose we want to apply blue color in column heading and magenta color in the task information.

 Quitting after certain iterations


The top command continuously displays output until you'll quit by pressing q.

But you can define certain number of iterations after which top command will automatically quit from the
terminal.

Syntax: top -n <number>


Example: top -n 2

4.8) last command:


The last command is used to find out last logged in timing of a user. It shows a list of last logged in
users from /var/log/wtmp file since this file was created. Hence, this list is too long.
It gives all related information like who is logged in, IP address (if there is a remote connection),
duration for logged in, date and time.

Look at the above snapshot,


 First column shows logged in user
 Second column shows how a user is connected to the system here, pts is pseudo terminal pts0
means user connects via remote connection system boot indicates the exception for reboot
activity
 Third column shows user's address if it shows :0 it means it is connected via local terminal it
shows IP address if it is connected via remote server kernel version is shown as the exception in
system reboot
 Remaining columns display timing activity of the users
 Bracket data indicates for how much time user was logged in

36
 Display full login and logout time
To display full login and logout information including date and time, option F is used.

Syntax: last -F

37
 Display specific username
To know the log in details of a specific user, use the username as argument of last command.

Syntax: last <username>

 Display reboot information


To know the reboot details, use following command

Syntax: last reboot

38
 Display specific pts
Make pts as an argument of the last command to print information about the specific pts.

Syntax: last pts


Example: last pts/0

4.9) ps command:
The ps command is used to view currently running processes on the system. It helps us to determine
which process is doing what in our system, how much memory it is using, how much CPU space it
occupies, user ID, command name, etc.

The ps command may display different results for different systems because it displays information
about the currently running process of a system.

 List running process in full format (ps –ef / ps –aux)


To display all currently running processes in full format on a system two types of commands are used.

Syntax: ps -ef

Look at the above snapshot, it display all the running processes on our system.

39
Syntax: ps -aux

Look at the above snapshot, this command filter the result by CPU or memory usage. It helps you in
determining how much memory is used or how much CPU space is used by a process.

 List all running process (ps –ax)


This command displays all the processes in a system. Here, a stands for all. It will display a long list of
result.

Syntax: ps -ax

40
 List process with specific username (ps –f –u)
Option u displays the process for a specific user. You can also specify multiple usernames separated by a
comma between them.

Syntax: ps -f -u <username>
Example: ps -f -u akki,sssit

 List process with specific command (ps –C)


Option C display a list of processes with the mentioned command as argument.

Syntax: ps -C <command>
Example: ps -C firefox

41
 Listing process in hierarchy (pstree / ps -axjf)
In normal ps command we have to look manually on PID and PPID number to know the relation between
processes. In hierarchical format, child processes are shown under the parent process which makes it easy
for us to look upon.

Syntax: pstree

Syntax: ps -axjf

42
 Show root running process (ps -U root -u root u)
It displays all the process running by root user.

Syntax: ps -U root -u root u

Here, -U parameter select real user ID,


-u parameter select effective user ID
last u parameter display output in user oriented format in columns.

4.10) Shutdown command:


The shutdown command brings down system in a secure way. All the logged-in users are notified
about the system shutdown.

Signal SIGTERM notifies all the processes that the system is going down, so that processes can be
saved and exit properly.

Command shutdown signals the init process to change the runlevel.


Runlevel 0 halts the system
Runlevel 6 reboots the system
Runlevel 1 is default state.

Five minutes before shutdown sequence starts, file /etc/nologin is created when shutdown is
scheduled for future which does not allow new user logins.
If by any reason, command shutdown is stopped before signalling init, this file is removed. It is also
removed to change runlevel before signaling init.
To run shutdown command root user access is required.

43
 Shutting down system
You can shutdown a system by passing a definite time (in minutes). System will automatically shutdown
after specified minute giving a message and time to save all work
.
Syntax: shutdown <time>
Example:shutdown 3

To immediately shutdown the system, use now option,

Syntax: shutdown now

 Rebooting the system (shutdown –r)


With option r, system will shutdown immediately and automatically reboot.

Syntax: shutdown -r <time>


Example: shutdown -r 3

 Power-off or halt-off the system (shutdown –h)


Option h decides whether the system will power-off or halt-off after shutting down.

Syntax: shutdown -h <time>


Example: shutdown -h 3

44
 power-off the system (shutdown –P)
To power-off the system option P is used. You don't have to manually power-off your system; this option
will automatically power-off your system.

Syntax: shutdown -P <time>


Example: shutdown -P 3

 Printing a message during shutdown


Admin can convey a message to all the logged in users stating reason for sudden shutdown.

Syntax: shutdown <time> <"message">


Example: shutdown 3 "message"

 Halt-off the system (shutdown –H)


Option H is used to halt-off the system after system is brought down.

Syntax: shutdown -H <time>


Example: shutdown -H 3

45
 Cancel shutdown (shutdown –c)
If due to any reason you want to cancel the shutdown command within the specified time, c option can be
used.

Syntax: shutdown -c

 Sending warnings and disabling logins (shutdown –k)


Option k will not halt or power-off the system, but just sends the warning and disable all the logins.
System will not actually shutdown.

Syntax: shutdown -k <time>


Example: shutdown -k 3

4.11) env command:


The env command is a shell command used to display and manipulate environment variables. It is
used to either list down environment variables or run a program in a modified environment.

With the help of env, commands can be added or removed; you can assign new values to the existing
variables.

46
4.12) du command:
Command du stands for Disk Usage. It is used to check the information of disk usage of files and
directories on a system.

Command du displays a list of all the files along with their respective sizes. By default, size given is
in kilobytes.

File names are used as arguments to get the file size.

4.13) Shred command:


The shred command allows us to delete our files securely making it very much difficult to recover that
file by anyone.
Erasing a file with rm command only erases the file system entry and keeps the content of the file intact.
It is quite easy to recover removed files content using some software’s.
To prevent from data recovering, shred overwrites the data multiple times by doing maximum
destruction of the data.
Shred can be used on files as well as devices such as hard disk partition. By default, shred overwrites file
three times with different patterns, but this number can be changed.
On normal deletion of file, that portion is simply marked to be used for another file, but data of that file is
still present. Those data can be retrieved through some advanced software’s.
This command is very much helpful when you want to permanently remove files containing sensitive
data. To remove this type of files rm command is not sufficient.

Syntax: shred <fileName>


Example: shred abc.txt

 To delete file
Use of shred command without any argument only overwrites the file content, but file still remains in the
file system.
To delete the file from the file system, use option u.

Syntax: shred -u <fileName>


Example: shred -u abc.txt

47
5) Linux User’s management

5.1) whoami command:


It tells you about the system's username.

5.2) who command:


The who command will give you information about who is logged on the system.

5.3) who am i command:


This command displays the information about the current user only.

48
5.4) w command:
This command tells about the users who are logged in and what are they doing.

5.5) id command:
This command tells about your user id, primary group id, and a list of groups that belongs to you.

5.6) su command:
The su command allows you to run a shell as another user.
Syntax: su <username>

49
 su to root
You can change the user to root when you know the root password.
Syntax: su root

 su as root:
The root user can become any existing user without knowing that user's password. Otherwise, password is
needed.

Example: su - sssit

 su - $username command:
The su command maintains the same shell environment. To become another user and also get the target
user's environment, issue the su - command followed by the target username.

50
 su – command:
If any user name is not mentioned then by default, it will assume root as the target user.

5.7) useradd command:


With useradd commands you can add a user.

Syntax: useradd -m -d /home/<userName> -c "<userName>" <userName>


Example: useradd -m -d /home/xyz -c "xyz" xyz

Look at the above snapshot, we have created a user xyz along with creating a home directory (-m), setting
the name of home directory (-d), and a description (-c).

5.8) userdel command:


To delete a user account userdel command is used.

Syntax: userdel -r <userName>


Example: userdel -r xyz

51
5.9) usermod command:
The command usermod is used to modify the properties of an existing user.

Syntax: usermod -c <'newName'> <oldName>


Example: usermod -c 'paddy123' paddy

Look at the above snapshot, user name paddy is replaced by the new user name paddy123

5.10) passwd command:


Passwords of users can be set with the passwd command. Users will have to provide their
old password before twice entering the new one.
Syntax: passwd <userName>
Example: passwd jtp

52
 Encryption With passwd
Passwords are always stored in encrypted format. Encryption is done with crypt function. The simplest
way to add a user with a password is to add the user with the command useradd -m and then set the
user's password with command passwd.

Syntax: useradd -m <userName>


Example: useradd -m akki
Syntax: passwd <typePassword>
Example: passwd ****

 Chage command
The chage command can be used by a user to know the information about their password. The -l option is
used to list the information.

Syntax: chage -l <userName>


Example: chage -l abc

53
 Disabling A Password
Passwords in /etc/shadow are not saved starting with exclamation mark (!). If exclamation mark is present
in starting then password cannot be used.

This feature can be used to disable a password and the process is called locking,
disabling and suspending a user account. It can be done in vi or with usermod command.
Here, we'll disable the password of akki with usermod command.

Syntax: usermod -L <userName>


Example: usermod -L akki

 Unlocking A Password
You can unlock your account with usermod -U.

Syntax: usermod -U <userName>


Example: usermod -U akki

54
5.11) Group command:
Users can be listed in different groups. Group allows us to set permission on the group level instead
of setting the permission on individual level.

 groupadd command

The groupadd command creates or add a group in our system.


Syntax: groupadd <groupName>
Example: groupadd php
groupadd java
groupadd android
groupadd spring

 groups command
The group command tells about the group where current user belongs to.

 usermod command
The group members can be edited with usermod or useradd command. If a group is not listed then by
default, usermod command will remove the user from every group of which he is a member. Here,
-a (append) option is used to prevent this from happening.

Syntax: usermod -a -G <group> <userName>


Example:
usermod -a -G php akki
usermod -a -G php abc
usermod -a -G java jtp

55
 groupmod command
With the help of groupmod command you can change the name of an already existing group.

Syntax: groupmod -n <newGroup> <oldGroup>


Example: groupmod -n sql spring

 groupdel command
The command groupdel will delete a group permanently from the system.

Syntax: groupdel <group>


Example: groupdel sql

56
6) Linux File Security

6.1) Linux File Ownership:


Every Linux system has three types of owner:
1. User: A user is the one who created the file. By default, whosoever, creates the file becomes
the owner of the file. A user can create, delete, or modify the file.
2. Group: A group can contain multiple users. All the users belonging to a group have same
access permission for a file.
3. Other: Any one who has access to the file other than user and group comes in the category
of other. Other has neither created the file nor is a group member.

Users and groups can be locally managed in /etc/psswd or /etc/group.

Syntax: ls -lh

6.2) Listing User Accounts:


To know the local users account, following command can be used. It list out all the local users from
the system.

Syntax: cut -d: -f1 /etc/passwd | column

57
6.3) Chgrp command:

The chgrp command can be abbreviated as change group. You can change the group owner of the
file using chgrp command.

Syntax: chgrp <newGroup> <fileName>


Example: chgrp php file

6.4) chown command:


Command chown is used to change the owner of the file.
Syntax: chown <newOwner> <fileName>
Example: chown jtp list

Command chown can also be used to change both user owner and group.
Syntax: chown <newOwner:newGroup> <fileName>
Example: chown jtp:php msg.txt

58
6.5) Setting Permissions With chmod

You can change the permissions with chmod command accordingly to your need.

 To add permissions to a group

Syntax: chmod <groupName>+<permissionName> <fileName>


Example: chmod u+x file

 To remove permissions from a group

Syntax: chmod <groupName>-<permissionName> <fileName>


Example: chmod g-x file
chmod u-w file

 To add permission to all the groups together

Syntax: chmod a+<permissionName> <fileName>


Example: chmod a+w file

59
 To set explicit permission

Syntax: chmod <groupName>=<permissions> <fileName>


Example: chmod o=rw file

 mkdir –m
The 'mkdir -m' command can be used to set the mode.

Syntax: mkdir -m <mode> <fileName>


Example: mkdir -m 777 new1
mkdir -m 000 new2

60
7) Linux Filter Commands

7.1) cat command:


When cat command is used inside pipes, it does nothing except moving stdin to stdout.

Syntax: cat <fileName> | cat or tac | cat or tac |. . .


Example: cat weeks.txt | tac | cat | cat | tac

7.2) cut command:

The 'cut' command is useful in selecting a specific column of a file. After (-d), delimiter (from where
you want to separate the columns) comes. Delimiters can be a space (' '), a hyphen (-), a slash (/) or
anything else. After (-f), column number is mentioned.

Syntax: cut -d(delimiter) -f(columnNumber) <fileName>

61
 Hyphen (-) As Delimiter
Syntax: cut -d- -f(columnNumber) <fileName>
Example: cut -d- -f2 marks.txt
cut -d- -f1 marks.txt

 Space As Delimiter
If you want to use space as a delimiter then you have to quote the space (' ').

Syntax: cut -d ' ' -f(columnNumber) <fileName>


Example: cut -d ' ' -f2 marks.txt
cut -d ' '-f5 marks.txt
cut -d ' '-f3 marks.txt

62
7.3) Grep command:
The 'grep' command stands for "global regular expression print". grep command filters the content
of a file which makes our search easy.

 grep with pipe

The 'grep' command is generally used with pipe (|).

Syntax: command | grep <searchWord>


Example:cat marks.txt | grep 9

 grep without pipe


It can be used without pipe also.

Syntax: grep <searchWord> <file name>


Example: grep 9 marks.txt

63
 grep options

--- grep -vM: The 'grep -v' command displays lines not matching to the specified word.

Syntax: grep -v <searchWord> <fileName>


Example: grep -v 9 marks.txt

--- grep -i: The 'grep -i' command filters output in a case-insensitive way.

Syntax: grep -i <searchWord> <fileName>


Example: grep -i red exm.txt

64
7.4) comm command:
The 'comm' command compares two files or streams. By default, 'comm' will always display three
columns. First column indicates non-matching items of first file, second column indicates non-
matching items of second file, and third column indicates matching items of both the files. Both the
files has to be in sorted order for 'comm' command to be executed.

Syntax: comm <file1> <file2>


Example: comm file1.txt file2.txt

 To Display Single Column

If you want to output a single column, you have to specify number of the columns which are not to be
displayed.

Syntax:
comm -23 (To display first column)
comm -13 (To display second column)
comm -12 (To display third column)

Example:
comm -23 file1.txt file2.txt
comm -13 file1.txt file2.txt
comm -12 file1.txt file2.txt

65
7.5) tr command:
The command 'tr' stands for 'translate'. It is used to translate, like from lowercase to uppercase and
vice versa or new lines into spaces.

 Change Case
The 'tr' command can change case.

Syntax: command | tr <'old'> <'new'>


Example: cat exm.txt | tr 'prcu' 'PRCU'

66
 Remove New Lines
To write all the lines into a single line we have to translate all new lines into spaces.

Syntax: command | tr <'\n'> <' '>


Example: cat exm.txt | tr '\n' ' '

 tr Options

--- tr -s : The 'tr -s' command squeezes the occurrence of multiple characters into one.

Syntax: command | tr -s <'letter'>


Example:
cat jtp.txt | tr -s 'l'
cat spaces.txt | tr -s ' '

67
--- tr rot13: This command encrypts the text. It is case-sensitive.

Example:
cat exm.txt | tr 'a-z' 'nopqrstuvwxyzabcdefghijklm'
cat exm.txt | tr 'a-z' 'n-za-m'

--- tr -d: The 'tr -d' command is used to delete characters.

Syntax: command | tr -d <letter>


Example: cat exm.txt | tr -d o

68
7.6) uniq command:
With the help of uniq command you can form a sorted list in which every word will occur only once.

Syntax: command <fileName> | uniq


Example: sort dupli.txt | uniq

 uniq –c command
You can count the number of occurences of a word with 'uniq -c' command.

Syntax: command <fileName> | uniq -c


Example:sort dupli.txt | uniq -c

7.7) wc command:
The 'wc' command helps in counting the lines, words and characters in a file.

Syntax:
wc <fileName> (Counts words, lines and characters)
wc -l <fileName> (Counts only lines)
wc -w <fileName> (Counts only words)
wc -c <fileName> (Counts only characters)

69
Example:
wc exm.txt
wc -l exm.txt
wc -w exm.txt
wc -c exm.txt

7.8) sort command:


The 'sort' command sorts the file content in an alphabetical order.

Syntax: sort <fileName>


Example: sort weeks.txt

70
 To Sort A Column
If a file has more than one column, column number is used to sort a specific column.

Syntax: sort -k<columnNumber> <fileName>


Example:
sort -k1 states.txt
sort -k2 states.txt

 Numeric Sorting
Numeric sorting is different from alphabetical sorting. For numeric sorting option 'n' is used along
with the column number if required.

Syntax: sort -n -k<columnNumber> <fileName>


Example: sort -n -k2 marks.txt

71
7.9) gzip command:
gzip (GNU zip) is a compressing tool, which is used to truncate the file size. By default original file
will be replaced by the compressed file ending with extension (.gz).

To decompress a file you can use gunzip command and your original file will be back.

Syntax:
gzip <file1> <file2> <file3>. . .
gunzip <file1> <file2> <file3>. . .

Example:
gzip file1.txt file2.txt
gunzip file1.txt file2.txt

 Compressing Multiple Files Together

If you want to compress more than one file together, you can use 'cat' and gzip command with pipe
command.

Syntax: cat <file1> <file2>. . | gzip > <newFile.gz>


Example: cat file1.txt file2.txt | gzip > final.gz

72
 gzip –l command
The 'gzip -l' command tells about the compression ratio or how much the original file has compressed.

Syntax: gzip -l <file1> <file2>. .


Example: gzip -l final.gz jtp.txt.gz

 To Compress A Directory
The gzip command will not be able to compress a directory because it can only compress a single file. To
compress a directory you have to use 'tar' command.

Hyphen (-) is not mandatory in 'tar' command.


'c' is to create,
'v' is for verbose, to display output,
'f' to mention destination of your output file,
'z' for specifying compress with gzip.

Syntax: tar cf - <directory> | gzip > <directoryName>


OR
tar cvfz office.tar.gz office
Example: tar cf - office | gzip > office.tar.gz

73
8) Linux Networking Commands
Every computer is connected to some other computer through a network whether internally or externally
to exchange some information. This network can be small as some computers connected in your home or
office, or can be large or complicated as in large University or the entire Internet.

8.1) ifconfig command:


The command ifconfig stands for interface configurator. This command enables us to initialize an
interface, assign IP address, enable or disable an interface. It display route and network interface.
You can view IP address, MAC address and MTU (Maximum Transmission Unit) with ifconfig
command.
A newer version of ifconfig is ip command. ifconfig command works for all the versions.

 Assigning IP address and Gateway


You can assign IP address and Gateway to an interface but these settings will be disabled after system
reboot.

Syntax: ifconfig eth0 <address> netmask <address>

 Enable or Disable specific interface


--- To enable specific interface,
Example: ifup eth0

--- To disable specific interface,


Example: ifdown eth0

74
 Setting MTU size
By default MTU (Maximum Transmission Unit) size is 1500, you can change size as per your wish.
Example: Ifconfig eth0 mtu xxxx

8.2) ip command:
This is the newer version of ifconfig command.
Syntax: ip a or ip addr

8.3) ping command:


The ping command stands for (Packet INternet Groper). It checks the connectivity between two
nodes that is whether a server is reachable or not.
ping command keep executing and sends the packet until you interrupt.
To stop from execution press ctrl + c.

 ping using DNS


Syntax: ping <destination>
Example: ping javatpoint.com

 ping using IP address


You can use IP address also with ping command.
Example: ping 2.2.2.2

 ping to limit the packets


To limit the ping packet without using ctrl + c use option c followed by the number of packet to be
send.
Syntax: ping -c <number> <destination>
Example: ping -c 5 javatpoint.com

75
8.4) host command:
This command displays domain name for given IP address and displays IP address for given domain
name. It also performs DNS lookups related to DNS query.

Example:
host javatpoint.com
host 144.76.11.18

76
9) Extra Command

9.1) find command:


The find command helps us to find a particular file within a directory. It is also used to find a list of files
having same pattern name.

After find command we may use following symbols:


(.) : For current directory name
(/) : For root

 Finding By Name
You can search all the files ending with extension '.txt'.
Example: find . -name "*.txt"

 Finding By Type
The '-type' parameter is used to specify the file type.
Some of the file types are:
f: regular file
d: directory
l:symbolic links
c: character devices
b: block devices

Example: find . -type d -name "*.bak"

77
9.2) locate command:
The command locate and find are used to search a file by their filename. But difference is that locate
command is a background process and searches the file in database whereas; find command searches in
file system. The locate command is much faster than find command.
If you are unable to find a file with locate command then it means that your database is out of date, and
you can update your database with the updatedb command.

Syntax: locate <fileName>


Example: locate sysctl.conf

9.3) date command


The date command displays date, time, time zone, etc.

Syntax: date

 Date Format
You can display the date in a format of your choice.

78
9.4) cal command:
The 'cal' term stands for calendar. It displays current month's calendar with current day highlighted.
Syntax: cal

 Displaying Past Or Future Month


You can also display past or future year's month with cal command.
Syntax: cal <month> <year>

9.5) Sleep command:


The sleep command let the terminal wait by the specified amount of time. By default it takes time in
seconds.

Syntax: sleep <time>


Example: sleep 5

79
9.6) zcat command:
Compressed files or zipped files can be viewed with the help of 'zcat' command.

Syntax: zcat <fileName>


Example: zcat acb

9.7) df command:
The 'df' command tells about the disk space used in the file system. It defines the number of blocks used,
number of blocks available and the directory where file system is mounted.

Syntax: df

80
10) References

1. https://www.mygov.in/sites/default/files/user_submission/920565a3edaa057078bcfc5b39665
68c.pdf

2. http://linux-training.be/linuxfun.pdf

81

You might also like