101 Linux Commands Ebook Dark
101 Linux Commands Ebook Dark
Usage ................................................................................................ 72
Compress a file ............................................................................ 73
Decompress a file ........................................................................ 74
Compress multiple files: .............................................................. 75
Decompress multiple files: .......................................................... 76
Compress a directory: ................................................................. 77
Decompress a directory: ............................................................. 78
Verbose (detailed) output while compressing: ............................ 79
Usage ................................................................................................ 84
Show memory usage ................................................................... 85
Show memory usage in human-readable form ............................ 86
16
Hacktoberfest
17
About me
DigitalOcean
If you are new to DigitalOcean, you can get a free $100 credit and spin
18
up your own servers via this referral link here:
DevDojo
The DevDojo is a resource to learn all things web development and web
design. Learn on your lunch break or wake up and enjoy a cup of coffee
with us to learn something new.
Join this developer community, and we can all learn together, build
together, and grow together.
Join DevDojo
19
Ebook PDF Generation Tool
20
Book Cover
21
License
MIT License
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
22
The ls command
The ls command lets you see the files and directories inside a specific
directory (current working directory by default). It normally lists the files
and directories in ascending alphabetical order.
Examples:
ls
ls {Directory_Path}
Syntax:
ls [-OPTION] [DIRECTORY_PATH]
Interactive training
In this interactive tutorial, you will learn the different ways to use the ls
command:
23
Additional Flags and their Functionalities:
Short
Long Flag Description
Flag
-l - Show results in long format
-S - Sort results by file size
-t - Sort results by modification time
Show files and directories in reverse order
-r --reverse
(descending alphabetical order)
Show all files, including hidden files (file
-a --all
names which begin with a period .)
Show long format files and directories
-la -
including hidden files
list long format files and directories with
-lh -
readable size
Shows all like -a but without showing
-A --almost-all .(current working directory) and .. (parent
directory)
Instead of listing the files and directories
inside the directory, it shows any
-d --directory information about the directory itself, it
can be used with -l to show long
formatted information
Appends an indicator character to the end
of each listed name, as an example: /
-F --classify
character is appended after each directory
name listed
like -l but displays file size in human-
-h --human-readable
readable unit not in bytes
1. Create the Alias: Define your alias with the desired options. For
24
example, to enhance the ls command:
25
The cd command
Examples of uses:
cd <specified_directory_path>
cd ~
OR
cd
26
cd -
This will also echo the absolute path of the previous directory.
cd /
Quick Tips
cd ..
This can also be done multiple times! For example, to move up three
folders:
cd ../../../
Syntax:
cd [OPTIONS] directory
Long
Short flag Description
flag
27
Long
Short flag Description
flag
Follow symbolic links. By default,cd behaves as if
-L -
the -L option is specified.
-P - Don’t follow symbolic links.
28
The cat command
The "cat" stands for 'concatenate.' and it's one of the most frequently
used commands in the Linux terminal.
Examples of uses:
cat <specified_file_name>
29
cat *.<filetype>
cat *
10. Some implementations of cat, with option -n, it's possible to show
line numbers:
30
Syntax:
Short
Long Flag Description
Flag
-A --show-all equivalent to -vET
number nonempty output lines,
-b --number-nonblank
overrides -n
-e - equivalent to -vE
Display tab separated lines in file
-T -
opened with cat command.
-E - To show $ at the end of each file.
-E - Display file with line numbers.
-n --number number all output lines
-s --squeeze-blank suppress repeated empty output lines
-u - (ignored)
use ^ and M- notation, except for LFD
-v --show-nonprinting
and TAB
- --help display this help and exit
- --version output version information and exit
31
The tac command
Examples of uses:
tac <specified_file_name>
32
tac --help
tac --version
Syntax:
Short
Long Flag Description
Flag
attach the separator before instead of
-b --before
after
interpret the separator as a regular
-r --regex
expression
use STRING as the separator instead of
-s --separator=STRING
newline
- --help display this help and exit
- --version output version information and exit
33
The head command
Example:
head filename.txt
Syntax:
Example:
head -n 10 foo.txt
This command will display the first ten lines of the file foo.txt.
Syntax:
34
Additional Flags and their Functionalities
Short
Long Flag Description
Flag
Print the first NUM bytes of each file;
with the leading '-',
-c --bytes=[-]NUM
print all but the last NUM bytes of each
file
Print the first NUM lines instead of the
first 10;
-n --lines=[-]NUM with the leading '-',
print all but the last NUM lines of each
file
-q --quiet, --silent Never print headers giving file names
-v --verbose Always print headers giving file names
-z --zero-terminated Line delimiter is NUL, not newline
--help Display this help and exit
--version Output version information and exit
35
The tail command
Example:
tail filename.txt
Syntax:
Example:
tail -n 10 foo.txt
This command will display the last ten lines of the file foo.txt.
It is possible to let tail output any new line added to the file you are
looking into. So, if a new line is written to the file, it will immediately be
shown in your output. This can be done using the --follow or -f
36
option. This is especially useful for monitoring log files.
Example:
tail -f foo.txt
Syntax:
Short
Long Flag Description
Flag
Output the last NUM bytes;
or use -c +NUM to
-c --bytes=[+]NUM
output starting with byte
NUM of each file
Output appended data as the
file grows;
-f --follow[={name|descriptor}]
an absent option argument
means 'descriptor'
Same as --follow=name --
-F
retry
Output the last NUM lines,
instead of the last 10;
-n --lines=[+]NUM
or use -n +NUM to output
starting with line NUM
37
Short
Long Flag Description
Flag
with --follow=name, reopen a
FILE which has not
changed size after N (default
5) iterations
to see if it has been unlinked
--max-unchanged-stats=N
or rename
(this is the usual case of
rotated log files);
with inotify, this option is
rarely useful
with -f, terminate after
--pid=PID
process ID, PID dies
Never output headers giving
-q --quiet, --silent
file names
keep trying to open a file if it
`` --retry
is inaccessible
With -f, sleep for
approximately N seconds
(default 1.0) between
-s --sleep-interval=N iterations;
with inotify and --pid=P,
check process P at
least once every N seconds
Always output headers giving
-v --verbose
file names
Line delimiter is NUL, not
-z --zero-terminated
newline
--help Display this help and exit
Output version information
--version
and exit
38
The pwd command
The pwd stands for Print Working Directory. It prints the path of the
current working directory, starting from the root.
Example:
pwd
/home/your_user/some_directory
Syntax:
pwd [OPTION]
Tip: You can also check this by printing out the $PWD variable:
echo $PWD
Options:
39
Short
Long Flag Description
Flag
If the environment variable $PWD contains an
absolute name of the current directory with no "."
-L --logical or ".." components, then output those contents,
even if they contain symbolic links. Otherwise, fall
back to default (-P) behavior.
Print a fully resolved name for the current
-P --physical directory, where all components of the name are
actual directory names, and not symbolic links.
--help Display a help message, and exit.
--version Display version information, and exit.
40
The touch Command
Syntax
Options
Short
Long Flag Description
Flag
-a - Change only the access time.
-c --no-create Do not create any files.
-d Parse STRING and use it instead of the
--date=STRING
STRING current time.
(Ignored) This option does nothing but is
-f - accepted to provide compatibility with
BSD versions of the touch command.
Affect each symbolic link instead of any
referenced file (useful only on systems
-h --no-dereference that can change the timestamps of a
symlink). This option implies -c, nothing
is created if the file does not exist.
-m - Change only the modification time.
Use this file's times instead of the current
-r=FILE --reference=FILE
time.
Use the numeric time STAMP instead of
-t
STAMP
- the current time. The format of STAMP is
[[CC]YY]MMDDhhmm[.ss].
41
Short
Long Flag Description
Flag
An alternate way to specify which type of
time is set (e.g. access, modification, or
- --time=WORD
change). This is equivalent to specifying
-a or -m.
An alternate way to specify what type of time to set (as with -a and -
m).| |
-
|--help|Display a help message, and exit.| |
-
|--version|Display version information, and exit.|
Examples
touch file.txt
2. If file.txt exists, set its times to the current system time. If it does
not exist, do nothing.
touch -c file.txt
42
touch -a file.txt
touch -h symboliclink
43
The cal Command
Syntax:
Options:
Option Description
-h Don't highlight today's date.
Specify a month to display. The month specifier is a full
month name (e.g., February), a month abbreviation of at
least three letters (e.g., Feb), or a number (e.g., 2). If you
-m month
specify a number, followed by the letter "f" or "p", the
month of the following or previous year, respectively,
display. For instance, -m 2f displays February of next year.
Specify a year to display. For example, -y 1970 displays
-y year
the entire calendar of the year 1970.
-3 Display last month, this month, and next month.
-1 Display only this month. This is the default.
Display num months occurring after any months already
specified. For example, -3 -A 3 displays last month, this
-A num month, and four months after this one; and -y 1970 -A 2
displays every month in 1970, and the first two months of
1971.
44
Option Description
Display num months occurring before any months already
-B num specified. For example, -3 -B 2 displays the previous
three months, this month, and next month.
-d YYYY- Operate as if the current month is number MM of year
MM YYYY.
Examples:
cal
cal -h
cal -3
cal -y
cal -y 2000
45
cal 2000
cal 12 2000
46
The bc command
Examples:
1 . Arithmetic:
2 . Increment:
3 . Decrement:
47
Input: $ echo "var=3;--var" | bc
Output: 2
4 . Assignment:
5 . Comparison or Relational:
48
Input: $ echo "2==2" | bc
Output: 1
6 . Logical or Boolean:
Syntax:
Short
Long Flag Description
Flag
-i --interactive Force interactive mode
-l --mathlib Use the predefined math routines
Opens the interactive mode for bc without
-q --quiet
printing the header
-s --standard Treat non-standard bc constructs as errors
Provides a warning if non-standard bc
-w --warn
constructs are used
49
Notes:
50
The df command
Syntax
df [OPTION]... [FILE]...
Options
Short
Long Flag Description
Flag
Include pseudo, duplicate,
-a --all
inaccessible file systems.
Scale sizes by SIZE before printing
them; e.g., -BM prints sizes in units of
-B --block-size=SIZE
1,048,576 bytes; see SIZE format
below.
Print sizes in powers of 1024 (e.g.,
-h --human-readable
1023M).
Print sizes in powers of 1000 (e.g.,
-H --si
1.1G).
List inode information instead of
-i --inodes
block usage.
-k - Like --block-size=1K.
51
Short
Long Flag Description
Flag
-l --local Limit listing to local file systems.
Do not invoke sync before getting
- --no-sync
usage info (default).
Use the output format defined by
- --output[=FIELD_LIST] FIELD_LIST, or print all fields if
FIELD_LIST is omitted.
-P --portability Use the POSIX output format
Invoke sync before getting usage
- --sync
info.
Elide all entries insignificant to
- --total available space, and produce a grand
total.
Limit listing to file systems of type
-t --type=TYPE
TYPE.
-T --print-type Print file system type.
Limit listing to file systems not of
-x --exclude-type=TYPE
type TYPE.
Ignored; included for compatibility
-v -
reasons.
- --help Display help message and exit.
- --version Output version information and exit.
Examples:
1. Show available disk space Action: --- Output the available disk
space and where the directory is mounted
Command:
df
52
2. Show available disk space in human-readable form Action: ---
Output the available disk space and where the directory is
mounted
Command:
df -h
3. Show available disk space for the specific file system Action: ---
Output the available disk space and where the directory is
mounted
Details: --- Outputted values are only for the selected file system
Command:
df -hT file_system_name
4. Show available inodes Action: --- Output the available inodes for
all file systems
Details: --- Outputted values are for inodes and not available space
Command:
df -i
5. Show file system type Action: --- Output the file system types
Command:
53
df -T
6. Exclude file system type from the output Action: --- Output the
information while excluding the chosen file system type
Details: --- Outputted values are for all file systems EXCEPT the chosen
file system type
Command:
df -x file_system_type
54
The help command
55
Syntax
56
Options
Option Description
-d Output short description for each topic.
-m Display usage in pseudo-manpage format.
Output only a short usage synopsis for each topic matching
-s
the provided PATTERN.
57
Examples of uses:
$ help cd
$ help -d pwd
$ help -s cd
58
The factor command
The factor command prints the prime factors of each specified integer
NUMBER. If none are specified on the command line, it will read them
from the standard input.
59
Syntax
$ factor [NUMBER]...
OR:
$ factor OPTION
60
Options
Option Description
--help Display this a help message and exit.
--version Output version information and exit.
61
Examples
$ factor 50
$ factor 75
62
The uname command
The uname command lets you print out system information and defaults
to outputting the kernel name.
63
Syntax:
$ uname [OPTION]
64
Examples
$ uname -a
$ uname -v
65
Options
Short
Long Flag Description
Flag
Print all information, except omit
-a --all processor and hardware platform if
unknown.
-s --kernel-name Print the kernel name.
-n --nodename Print the network node hostname.
-r --kernel-release Print the kernel release.
-v --kernel-version Print the kernel version.
-m --machine Print the machine hardware name.
Print the processor type (non-
-p --processor
portable).
Print the hardware platform (non-
-i --hardware-platform
portable).
-o --operating-system Print the operating system.
66
The mkdir command
67
Syntax
68
Examples
$ mkdir myfiles
$ mkdir ~/myfiles
3. Create the mydir directory, and set its file mode (-m) so that all
users (a) may read (r), write (w), and execute (x) it.
For directories, this means that any user on the system may view
("read"), and create/modify/delete ("write") files in the directory. Any
user may also change to ("execute") the directory, for example with the
cd command.
$ mkdir -p /home/test/src/python
69
Options
Short
Long Flags Descriptions
Flags
Set file mode (as in chmod), not a=rwx -
-m --mode=MODE
umask.
No error if existing, make parent directories
-p --parents
as needed.
-v --verbose Print a message for each created directory.
Set the SELinux security context of each
-Z --context=CTX
created directory to CTX.
- --help Display a help message and exit.
- --version Output version information and exit.
70
The gzip command
71
Usage
72
Compress a file
Command:
gzip file_name
73
Decompress a file
Details: --- Restore the file's original form in terms of data and size
Command:
gzip -d archive_01.gz
74
Compress multiple files:
Command:
75
Decompress multiple files:
Command:
76
Compress a directory:
Command:
gzip -r directory_name
77
Decompress a directory:
Details: --- Decompress multiple files under a directory from one single
archive
Command:
78
Verbose (detailed) output while compressing:
Details: --- Output more information about the action of the command
Command:
gzip -v file_name
79
The whatis command
Examples of uses:
whatis ls
2. To display the use of all commands which start with make, execute
the following:
whatis -w make*
Syntax:
80
The who command
The who command lets you print out a list of logged-in users, the
current run level of the system and the time of last system boot.
Examples
who -a
who -d -H
Syntax:
81
Short Flag Description
-b print the time of last system boot
018-the-free-command.md
82
The free command
83
Usage
84
Show memory usage
Action: --- Output the memory usage - available and used, as well as
swap
Command:
free
85
Show memory usage in human-readable form
Action: --- Output the memory usage - available and used, as well as
swap
Command:
free -h
86
The top/htop command
87
Comparison between top and htop:
88
Examples:
top
top
top -o mem
htop
htop
89
htop --user {user_name}
90
Syntax:
top [OPTIONS]
htop [OPTIONS]
91
Additional Flags and their Functionalities:
Short Long
Description
Flag Flag
-a - Sort by memory usage.
Batch mode operation. Starts top in 'Batch mode',
which could be useful for sending output from top to
-b - other programs or to a file. In this mode, top will not
accept input and runs until the iterations limit you've
set with the '-n' command-line option or until killed.
top --user {user_name} Only display processes
-h -
owned by user.
-U -user Help.
-u - This is an alias equivalent to: -o cpu -O time.
92
The sl command
93
Installation
94
Syntax
sl
95
The echo command
The echo command lets you display the line of text/string that is passed
as an argument
Examples:
echo *
Syntax:
96
echo [option] [string]
Option Description
\b removes all the spaces in between the text
suppress trailing new line with backspace interpretor ‘-e‘ to
\c
continue without emitting new line.
\n creates new line from where it is used
\t creates horizontal tab spaces
carriage returns with backspace interpretor ‘-e‘ to have
\r
specified carriage return in output
\v creates vertical tab spaces
alert returns with a backspace interpretor ‘-e‘ to have sound
\a
alert
-n omits echoing trailing newline .
97
The finger command
Examples:
finger abc
Output
finger -s root
Output
98
Login Name Tty Idle Login Time
Office Office Phone
root root *1 19d Wed 17:45
root root *2 3d Fri 16:53
root root *3 Mon 20:20
root root *ta 2 Tue 15:43
root root *tb 2 Tue 15:44
Syntax:
Flag Description
-l Force long output format.
-m Match arguments only on user name (not first or last name).
-p Suppress printing of the .plan file in a long format printout.
-s Force short output format.
Additional Information
Default Format
Login name
Full username
Terminal name
Write status (an * (asterisk) before the terminal name indicates that
write permission is denied)
For each user on the host, the default information list also includes, if
known, the following items:
99
Idle time (Idle time is minutes if it is a single integer, hours and minutes
if a : (colon) is present, or days and hours if a “d” is present.)
Login time
Site-specific information
Longer Format
100
The groups command
Important Points:
The groups command prints the names of the primary and any
supplementary groups for each given username, or the current process
if no names are given. If more than one name is given, the name of
each user is printed before the list of that user’s groups and the
username is separated from the group list by a colon.
Syntax:
groups [username]
Example 1
groups demon
101
Example 2
groups
Here the current user is demon . So when we run the groups command
without arguments we get the groups in which demon is a user.
Example 3
$demon# groups
102
The man command
The man command is used to display the manual of any command that
we can run on the terminal. It provides information like: DESCRIPTION,
OPTIONS, AUTHORS and more.
Examples:
man printf
man 2 intro
man -l [LOCAL-FILE]
Syntax:
103
Additional Flags and their Functionalities:
Short Long
Description
Flag Flag
-f - Return the sections of an command
-a - Display all the manual pages of an command
Searches the given command with RegEx in all
-k -
man pages
Returns the location of a given command man
-w -
page
-I - Searches the command manual case sensitive
104
The passwd command
105
Example
$ passwd
106
The syntax of the passwd command is :
107
options
-a, --all
This option can be used only with -S and causes show
status for all users.
-d, --delete
Delete a user's password.
-e, --expire
Immediately expire an account's password.
-h, --help
Display help message and exit.
-i, --inactive
This option is used to disable an account after the
password has been expired for a number of days.
-k, --keep-tokens
Indicate password change should be performed only for
expired authentication tokens (passwords).
-l, --lock
Lock the password of the named account.
-q, --quiet
Quiet mode.
-r, --repository
change password in repository.
-S, --status
Display account status information.
108
The w command
The w command displays information about the users that are currently
active on the machine and their processes.
Examples:
w hope
Syntax:
Short
Long Flag Description
Flag
-h --no-header Don't print the header.
109
Short
Long Flag Description
Flag
Ignores the username while figuring out the
current process and cpu times. (To see an
-u --no-current
example of this, switch to the root user with
su and then run both w and w -u.)
Display abbreviated output (don't print the
-s --short
login time, JCPU or PCPU times).
Toggle printing the from (remote hostname)
field. The default as released is for the from
field to not be printed, although your system
-f --from
administrator or distribution maintainer may
have compiled a version where the from field
is shown by default.
--help - Display a help message, and exit.
-V --version Display version information, and exit.
Old style output (prints blank space for idle
-o --old-style
times less than one minute).
Show information about the specified the user
user -
only.
Additional Information
The header of the output shows (in this order): the current time, how
long the system has been running, how many users are currently
logged on, and the system load averages for the past 1, 5, and 15
minutes.
110
command line of their current process
The JCPU time is the time used by all processes attached to the tty. It
does not include past background jobs, but does include currently
running background jobs.
The PCPU time is the time used by the current process, named in the
"what" field.
111
The whoami command
manish@godsmack:~$ whoami
# Output:
manish
Syntax:
whoami [-OPTION]
Example:
whoami --help
Output:
112
Usage: whoami [OPTION]...
Print the user name associated with the current effective user
ID.
Same as id -un.
Example:
whoami --version
Output:
113
The history command
If you type history you will get a list of the last 500 commands used.
This gives you the possibility to copy and paste commands that you
executed in the past.
Examples:
1. If you want to search in your history for artisan commands you ran
in the past.
history 10
114
The login Command
115
Syntax
116
Flags and their functionalities
Short
Description
Flag
Used to skip a login authentication. This option is usually
-f
used by the getty(8) autologin feature.
Used by other servers (such as telnetd(8) to pass the name
-h of the remote host to login so that it can be placed in utmp
and wtmp. Only the superuser is allowed use this option.
-p Used by getty(8) to tell login to preserve the environment.
Used by other servers (for example, telnetd(8)) to tell login
-H that printing the hostname should be suppressed in the
login: prompt.
--help Display help text and exit.
-v Display version information and exit.
117
Examples
To log in to the system as user abhishek, enter the following at the login
prompt:
$ login: abhishek
118
lscpu command
For example :
manish@godsmack:~$ lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 2
Core(s) per socket: 2
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 142
Model name: Intel(R) Core(TM) i5-7200U CPU @
2.50GHz
Stepping: 9
CPU MHz: 700.024
CPU max MHz: 3100.0000
CPU min MHz: 400.0000
BogoMIPS: 5399.81
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 256K
L3 cache: 3072K
NUMA node0 CPU(s): 0-3
119
Options
-a, --all Include lines for online and offline CPUs in the output
(default for -e). This option may only specified together with option -e or
-p. For example: lsof -a
-b, --online Limit the output to online CPUs (default for -p). This
option may only be specified together with option -e or -p. For example:
lscpu -b
-c, --offline Limit the output to offline CPUs. This option may only be
specified together with option -e or -p.
120
The cp command
Examples:
cp sourceFile destFile
If the destination file doesn't exist then the file is created and the
content is copied to it. If it exists then the file is overwritten.
cp sourceFile /folderName/destFile
cp -R folderName1 folderName2
121
directory.
If the destination directory already exists, the source directory itself and
its content are copied inside the destination directory.
4. To copy only the files and subdirectories but not the source
directory
Syntax:
The first and second syntax is used to copy Source file to Destination
file or Directory. The third syntax is used to copy multiple Sources(files)
to Directory.
$ cp -i file1.txt fileName2.txt
cp: overwrite 'file2.txt'? y
122
backup of the destination file in the same folder with the different
name and in different format.
$ ls
a.txt b.txt
$ cp -b a.txt b.txt
$ ls
a.txt b.txt b.txt~
$ ls -l b.txt
-r-xr-xr-x+ 1 User User 3 Nov 24 08:45 b.txt
$ cp a.txt b.txt
cp: cannot create regular file 'b.txt': Permission denied
$ cp -f a.txt b.txt
123
Additional Flags and their Functionalities:
Short
Long Flag Description
Flag
-i --interactive prompt before overwrite
If an existing destination file cannot be opened,
-f --force
remove it and try again
Creates the backup of the destination file in the
-b - same folder with the different name and in
different format.
cp command shows its recursive behavior by
-r or
--recursive copying the entire directory structure
-R
recursively.
do not overwrite an existing file (overrides a
-n --no-clobber
previous -i option)
preserve the specified attributes (default:
-p - mode,ownership,timestamps), if possible
additional attributes: context, links, xattr, all
124
The mv command
Syntax:
Examples:
mv old_name.txt new_name.txt
mv essay.txt assignments/essay1.txt
125
directory called assignments without renaming it
mv essay.txt assignments
Short
Long Flag Description
Flag
Force move by overwriting destination file
-f --force
without prompt
-i --interactive Interactive prompt before overwrite
Move only when the source file is newer than
-u --update the destination file or when the destination
file is missing
-n --no-clobber Do not overwrite an existing file
-v --verbose Print source and destination files
-b --backup Create a Backup of Existing Destination File
126
The ps command
Let's say you have a program like openshot which is notorious for
hogging system resources when exporting a video, and you want to
close it, but the GUI has become unresponsive.
Example
ps -A
Syntax
ps [options]
When run without any options, it's useless and will print: CMD - the
executable processes/(program) running, their PID - process ID, TTY -
127
terminal type and Time - How long the process has utilized the CPU or
thread.
Common Option
If you are going to remember only one thing from this page let it be
these three letter aux: a - which displays all processes running,
including those being run by other users. u - which shows the effective
user of a process, i.e. the person whose file access permissions are
used by the process. x - which shows processes that do not have a TTY
associated with them.
Additional Options:
Option Description
a Shows list all processes with a terminal (tty)
-A Lists all processes. Identical to -e
Shows all processes except both session leaders and
-a
processes not associated with a terminal
-d Select all processes except session leaders
Shows all processes except those that fulfill the
--deselect
specified conditions. Identical to -N
-e Lists all processes. Identical to -A
Shows all processes except those that fulfill the
-N
specified conditions. Identical to -deselect
Select all processes associated with this terminal.
T
Identical to the -t option without any argument
r Restrict the selection to only running processes
--help simple Shows all the basic options
--help all Shows every available options
128
The kill command
Syntax
Examples:
1. To display all the available signals you can use below command
option:
kill -l
129
$kill pid
4. Specify Signal:
kill -9 pid
Arguments:
130
pid Each pid can be expressed in one of the following
ways:
Options:
131
-s, --signal signal
The signal to send. It may be given as a name or a
number.
-L, --table
Similar to -l, but it will print signal names and
their corresponding numbers.
-a, --all
Do not restrict the command-name-to-PID conversion
to processes with the same UID
as the present process.
-p, --pid
Only print the process ID (PID) of the named
processes, do not send any signals.
--verbose
Print PID(s) that will be signaled with kill along
with the signal.
132
The killall command
killall returns a zero return code if at least one process has been
killed for each listed command, or no commands were listed and at
least one process matched the -u and -Z search criteria. killall
returns non-zero otherwise.
A killall process never kills itself (but may kill other killall
processes).
Examples:
killall conky
# OR
killall -SIGTERM conky
# OR
kilall -15 conky
I was able to kill Wine ( which are Windows exe files running on Linux )
133
applications this way too.
killall TQ.exe
$ killall -l
HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE
ALRM TERM STKFLT
CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH
POLL PWR SYS
134
$ for s in $(killall -l); do echo -n "$s " && kill -l $s; done
HUP 1
INT 2
QUIT 3
ILL 4
TRAP 5
ABRT 6
BUS 7
FPE 8
KILL 9
USR1 10
SEGV 11
USR2 12
PIPE 13
ALRM 14
TERM 15
STKFLT 16
CHLD 17
CONT 18
STOP 19
TSTP 20
TTIN 21
TTOU 22
URG 23
XCPU 24
XFSZ 25
VTALRM 26
PROF 27
WINCH 28
POLL 29
PWR 30
SYS 31
$ killall -i conky
Kill conky(1685) ? (y/N)
135
killall -w conky
Syntax:
Short
Long Flag Description
Flag
require an exact match for very long
-e --exact
names
-I --ignore-case case insensitive process name match
-g --process-group kill process group instead of process
-y --younger-than kill processes younger than TIME
-o --older-than kill processes older than TIME
-i --interactive ask for confirmation before killing
-l --list list all known signal names
-q --quiet don't print complaints
interpret NAME as an extended regular
-r --regexp
expression
-s --signal SIGNAL send this signal instead of SIGTERM
136
Short
Long Flag Description
Flag
-u --user USER kill only process(es) running as USER
-v --verbose report if the signal was successfully sent
-w --wait wait for processes to die
match processes that belong to the same
-n --ns PID
namespaces as PID
REGEXP kill only process(es) having
-Z --context
context (must precede other arguments)
Related commands
kill, pidof
137
The env command
138
Syntax
139
Usage
env
env -i command_name
env -u variable_name
env -0
140
Full List of Options
Short
Long Flag Description
Flag
-i --ignore-environment Start with an empty environment
End each output line with NUL, not
-0 --null
newline
Remove variable from the
-u --unset=NAME
environment
-C --chdir=DIR Change working directory to DIR
Process and split S into separate
-S --split-string=S arguments. It's used to pass multiple
arguments on shebang lines
Print verbose information for each
-v --debug
processing step
- --help Print a help message
- --version Print the version information
141
The printenv command
Examples:
printenv
printenv HOME
Syntax:
142
printenv [OPTION]... PATTERN...
143
The hostname command
Syntax:
Examples:
Help Command
144
command.
man hostname
145
The nano command
Installation:
Nano text editor is pre-installed on macOS and most Linux distros. It's
an alternative to vi and vim. To check if it is installed on your system
type:
nano --version
If you don't have nano installed you can do it by using the package
manager:
Ubuntu or Debian:
Examples:
1. Open an existing file, type nano followed by the path to the file:
nano /path/to/filename
146
nano filename
3. Open a file with the cursor on a specific line and character use the
following syntax:
Shortcut Description
Ctrl + S Save current file
Ctrl + O Offer to write file ("Save as")
Ctrl + X Close buffer, exit from nano
Ctrl + K Cut current line into cutbuffer
Ctrl + U Paste contents of cutbuffer
Alt + 6 Copy current line into cutbuffer
Alt + U Undo last action
Alt + E Redo last undone action
147
The rm command
Example:
rm filename.txt
Syntax
rm [OPTION] [FILE|DIRECTORY]
Short
Long Flag Description
Flag
Ignore nonexistance of files or
-f --force
directories, never prompt
-i - Prompt before every removal
Prompt once before removal of more
-I - than 3 files, or when removing
recursively
-d --dir remove empty directories
-v --verbose explain what is being done
-r or - remove directories and their contents
--recursive
R recursively
148
Short
Long Flag Description
Flag
- --help Display help then exit
First, Print version Information, Then
- --version
exit
- --no-preserve-root do not treat / specially
do not remove / (default)
with 'all', reject any command line
- -preserve-root[=all]
argument on a separate device from
its parent
prompt according to WHEN, never,
- --interactive[=WHEN] once -I, or always -i, without WHEN,
prompt always
when removing a hierarchy
recursively, skip any directory that is
- --one-file-system on a file system different from that of
the corresponding command line
argument0
IMPORTANT NOTICE:
149
The ifconfig command
Syntax:
Examples:
ifconfig
ifconfig -a
150
ifconfig -v
ifconfig -s
ifconfig eth0
ifconfig eth0 up
151
ifconfig eth0 netmask 255.255.255.224
The MTU allows you to set the limit size of packets that are transmitted
on an interface. The MTU is able to handle a maximum number of
octets to an interface in one single transaction.
Please note that the alias network address is in the same subnet mask
of the network interface. For example, if your eth0 network ip address is
152
10.10.1.23, then the alias ip address can be 10.10.1.24. Example of
an invalid IP address is 10.10.2.24 since the interface subnet mask is
255.255.255.224
Remember that for every scope (i.e. same net with address/netmask
combination) all aiases are deleted, if you delete the first alias.
Help Command
man ifconfig
153
The ip command
Examples:
ip addr show
Syntax:
154
Additional Flags and their Functionalities:
Flag Description
-a Display and modify IP Addresses
-l Display and modify network interfaces
-r Display and alter the routing table
-n Display and manipulate neighbor objects (ARP table)
-ru Rule in routing policy database.
Output more information. If the option appears twice or more, the
-s
amount of information increases
-f Specifies the protocol family to use
Use the system's name resolver to print DNS names instead of
-r
host addresses
-c To configure color output
155
The clear command
156
Example
$ clear
157
Before:
$ clear
158
After executing clear command:
Screenshot:
159
The su command
160
Example :
$ su
In case that you wanted to switch to a user called devdojo, you could
do that by running the following command:
$ su devdojo
161
The syntax of the su command is :
162
Options :
163
The wget command
The wget command is used for downloading files from the Internet. It
supports downloading files using HTTP, HTTPS and FTP protocols. It
allows you to download several files at once, download in the
background, resume downloads, limit the bandwidth, mirror a website,
and much more.
164
Syntax
The wget syntax requires you to define the downloading options and the
URL the to be downloaded file is coming from.
Examples
In this example we will download the Ubuntu 20.04 desktop iso file from
different sources. Go over to your terminal or open a new one and type
in the below wget. This will stat the download. The download may take
a few minutes to complete.
wget
https://releases.ubuntu.com/20.04/ubuntu-20.04.3-desktop-amd64
.iso
wget -c
https://mirrors.piconets.webwerks.in/ubuntu-mirror/ubuntu-rele
ases/20.04.3/ubuntu-20.04.3-desktop-amd64.iso
165
wget -b
https://mirrors.piconets.webwerks.in/ubuntu-mirror/ubuntu-rele
ases/20.04.3/ubuntu-20.04.3-desktop-amd64.iso
166
More options
man wget
Short
Description
Flag
-v prints version of the wget available on your system
-h print help message displaying all the possible options
This option is used to send a process to the background as
-b
soon as it starts.
This option is used to set number of retries to a specified
-t
number of times
-c This option is used to resume a partially downloaded file
167
The curl command
168
Example :
$ curl example.com
The command will print the source code of the example.com homepage
in the terminal window.
169
The syntax of the curl command is :
170
Options :
Options start with one or two dashes. Many of the options require an
additional value next to them.
Short version options that don't need any additional values can be used
immediately next to each other, like for example you can specify all the
options -O, -L and -v at once as -OLv.
In general, all boolean options are enabled with --option and yet again
disabled with --no-option. That is, you use the exact same option
name but prefix it with no-. However, in this list we mostly only list and
show the --option version of them. (This concept with --no options
was added in 7.19.0. Previously most options were toggled on/off
through repeated use of the same command line option.)
171
Installation:
The curl command comes with most of the Linux distributions. But, if
the system does not carry the curl by default. You need to install it
manually. To install the curl, execute the following commands:
$ curl -version
The above command will display the installed version of the curl
command.
172
The yes command
Examples :
yes [STRING]
173
Options
1. --help
display this help and exit
2. --version
output version information and exit
174
The last command
This command shows you a list of all the users that have logged in and
out since the creation of the var/log/wtmp file. There are also some
parameters you can add which will show you for example when a
certain user has logged in and how long he was logged in for.
If you want to see the last 5 logs, just add -5 to the command like this:
last -5
Another cool thing you can do is if you add -F you can see the login and
logout time including the dates.
last -F
There are quite a lot of stuff you can view with this command. If you
need to find out more about this command you can run:
last --help
175
The locate command
The locate command searches the file system for files and directories
whose name matches a given pattern through a database file that is
generated by the updatedb command.
Examples:
locate .bashrc
Output
/etc/bash.bashrc
/etc/skel/.bashrc
/home/linuxize/.bashrc
/usr/share/base-files/dot.bashrc
/usr/share/doc/adduser/examples/adduser.local.conf.examples/ba
sh.bashrc
/usr/share/doc/adduser/examples/adduser.local.conf.examples/sk
el/dot.bashrc
The /root/.bashrc file will not be shown because we ran the command
as a normal user that doesn’t have access permissions to the /root
directory.
If the result list is long, for better readability, you can pipe the output to
the less command:
176
locate .bashrc | less
locate *.md
locate -n 10 *.py
locate -i readme.md
Output
/home/linuxize/p1/readme.md
/home/linuxize/p2/README.md
/home/linuxize/p3/ReadMe.md
locate -c .bashrc
Output
6. The following would return only the existing .json files on the file
177
system.
locate -e *.json
Syntax:
Short
Long Flag Description
Flag
It is used to display only entries that
-A --all match all PATTERNs instead of requiring
only one of them to match.
It is used to match only the base name
-b --basename
against the specified patterns.
It is used for writing the number
-c --count matching entries instead of writing file
names on standard output.
It is used to replace the default
-d --database DBPATH
database with DBPATH.
It is used to display only entries that
-e --existing refer to existing files during the
command is executed.
178
Short
Long Flag Description
Flag
If the --existing option is specified, It
is used for checking whether files exist
and follow trailing symbolic links. It will
-L --follow omit the broken symbolic links to the
output. This is the default behavior. The
opposite behavior can be specified
using the --nofollow option.
It is used to display the help
-h --help documentation that contains a
summary of the available options.
It is used to ignore case sensitivity of
-i --ignore-case
the specified patterns.
It is used to ignore punctuation and
-p --ignore-spaces
spaces when matching patterns.
It is used to ignore accents using iconv
-t --transliterate
transliteration when matching patterns.
If this option is specified, the command
-l --limit, -n LIMIT exit successfully after finding LIMIT
entries.
It is used to ignore the compatibility
-m --mmap
with BSD, and GNU locate.
It is used to separate the entries on
output using the ASCII NUL character
-0 --null
instead of writing each entry on a
separate line.
It is used to write statistics about each
-S --statistics read database to standard output
instead of searching for files.
It is used for searching a basic regexp
-r --regexp REGEXP
REGEXP.
It is used to describe all PATTERNs as
--regex -
extended regular expressions.
It is used to display the version and
-V --version
license information.
It is used for matching only the whole
-w --wholename
path name in specified patterns.
179
The iostat command
Syntax:
iostat [ -c ] [ -d ] [ -h ] [ -N ] [ -k | -m ] [ -t ] [ -V ] [
-x ]
[ -z ] [ [ [ -T ] -g group_name ] { device [...] | ALL
} ]
[ -p [ device [,...] | ALL ] ] [ interval [ count ] ]
Examples:
iostat -d 2
iostat -d 2 6
180
3.Display, for all devices, six reports at two-second intervals:
4.Display, for devices sda and sdb, six extended reports at two-second
intervals:
iostat -p sda 2 6
181
The sudo command
The sudo ("substitute user do" or "super user do") command allows a
user with proper permissions to execute a command as another user,
such as the superuser.
WARNING: Be very careful when using the sudo command. You can
cause irreversible and catastrophic changes while acting as root!
Syntax:
Flag Description
The -V (version) option causes sudo to print the version number
and exit. If the invoking user is already root, the -V option prints
-V
out a list of the defaults sudo was compiled with and the
machine's local network addresses
The -l (list) option prints out the commands allowed (and
-l
forbidden) the user on the current host.
182
Flag Description
The -L (list defaults) option lists out the parameters set in a
-L Defaults line with a short description for each. This option is
useful in conjunction with grep.
The -h (help) option causes sudo to print a usage message and
-h
exit.
If given the -v (validate) option, sudo updates the user's
timestamp, prompting for the user's password if necessary. This
-v
extends the sudo timeout for another 5 minutes (or whatever the
timeout is set to in sudoers) but does not run a command.
The -K (sure kill) option to sudo removes the user's timestamp
-K
entirely. Likewise, this option does not require a password.
The -u (user) option causes sudo to run the specified command
-u as a user other than root. To specify a uid instead of a username,
use #uid.
The -s (shell) option runs the shell specified by the SHELL
-s environment variable if it's set or the shell as specified in the file
passwd.
The -- flag indicates that sudo should stop processing command
--
line arguments. It is most useful in conjunction with the -s flag.
183
Examples
sudo bash
root@hostname:/home/[username]
Example:
184
The apt command
You will be using the apt command mostly with sudo privileges.
Installing packages:
Syntax:
Example:
185
Removing packages:
Syntax:
Example:
Syntax:
Example:
186
Removing unused packages:
Syntax:
Syntax:
Upgrading packages:
If you want to install the latest updates for your installed packages you
may want to run this command.
187
Syntax:
Syntax:
188
The yum command
Syntax:
Examples:
yum history
189
yum -y install firefox
Command Description
install Installs the specified packages
remove Removes the specified packages
search Searches package metadata for keywords
info Lists the description
update Updates each package to the latest version
repolist Lists repositories
history Displays what has happened in past transactions
groupinstall To install a particular package group
clean To clean all cached files from enabled repository
Short
Long Flag Description
Flag
Runs entirely from system cache, doesn’t
-C --cacheonly update the cache and use it even in case it is
expired.
Includes packages that provide a fix for a
- --security security issue. Applicable for the upgrade
command.
-y --assumeyes Automatically answer yes for all questions.
190
Short
Long Flag Description
Flag
Resolves depsolve problems by removing
packages that are causing problems from the
- --skip-broken
transaction. It is an alias for the strict
configuration option with value False.
-v --verbose Verbose operation, show debug messages.
191
The zip command
The zip command is used to compress files and reduce their size. It
outputs an archive containing one or more compressed files or
directories.
Examples:
In order to compress a single file with the zip command the syntax
would be the following:
Syntax:
192
Possible options:
Flag Description
Removes the file from the zip archive. After creating a zip file,
-d
you can remove a file from the archive using the -d option
Updates the file in the zip archive. This option can be used to
update the specified list of files or add new files to the existing
-u zip file. Update an existing entry in the zip archive only if it has
been modified more recently than the version already in the zip
archive.
-m Deletes the original files after zipping.
To zip a directory recursively, it will recursively zip the files in a
-r directory. This option helps to zip all the files present in the
specified directory.
-x Exclude the files in creating the zip
Verbose mode or print diagnostic version info. Normally, when
applied to real operations, this option enables the display of a
-v
progress indicator during compression and requests verbose
diagnostic info about zip file structure oddities
193
The unzip command
The unzip command extracts all files from the specified ZIP archive to
the current directory.
Examples:
unzip myZipFile.zip
To unzip a ZIP file to a different directory than the current one, don't
forget to add the -d flag:
To unzip a ZIP file and exclude specific file or files or directories from
being extracted, don't forget to add the -x flag:
Syntax:
194
Possible options:
195
The shutdown command
The shutdown command lets you bring your system down in a secure
way. When shutdown is executed the system will notify all logged-in
users and disallow further logins. You have the option to shut down your
system immediately or after a specific time.
Only users with root (or sudo) privileges can use the shutdown
command.
Examples:
Syntax:
196
shutdown [OPTIONS] [TIME] [MESSAGE]
197
The dir command
Syntax:
Examples:
dir
dir -a
dir -l
198
Additional Flags and their Functionalities:
Short
Long Flag Description
Flag
It displays all the hidden
-a --all files(starting with .) along with
two files denoted by . and ..
It is similar to -a option except
that it does not display files that
-A --almost-all
signals the current directory and
previous directory.
Display detailed information for
-l -
each entry
Print the allocated size of each
-s --size
file, in blocks File
Used with with -l and -s, to print
-h --human-readable sizes like in human readable
format like 1K, 2M and so on
Classifies entries into their type
-F - based on appended symbol (/,
*, @, %, =)
-v --verbose Print source and destination files
- --group-directories-first To group directories before files
To List subdirectories
-R --recursive
recursively.
sort by file size, display largest
-S -
first
199
The reboot Command
200
Syntax
reboot [OPTIONS...]
Options
Examples
$ sudo reboot
Note that the usage of the reboot, halt and power off is almost similar
in syntax and effect. Run each of these commands with –help to see the
details.
201
$ sudo shutdown –r [TIME] [MESSAGE]
Here the TIME has various formats. The simplest one is now, already
been listed in the previous section, and tells the system to restart
immediately. Other valid formats we have are +m, where m is the
number of minutes we need to wait until restart and HH:MM which
specifies the TIME in a 24hr clock.
$ sudo shutdown –r +2
Syntax
Usage
202
$ last reboot
203
The sort command
Examples:
Command :
$ cat > file.txt
abhishek
chitransh
satish
rajan
naveen
divyam
harsh
Syntax :
sort filename.txt
204
Command:
$ sort file.txt
Output :
abhishek
chitransh
divyam
harsh
naveen
rajan
satish
Note: This command does not actually change the input file, i.e. file.txt.
i.e. uppercase and lower case: When we have a mix file with both
uppercase and lowercase letters then first the upper case letters would
be sorted following with the lower case letters.
Example:
Command :
$ cat > mix.txt
abc
apple
BALL
Abc
bat
205
Command :
$ sort mix.txt
Output :
Abc
BALL
abc
apple
bat
206
The paste command
The paste command writes lines of two or more files, sequentially and
separated by TABs, to the standard output
Syntax:
Examples:
Short
Long Flag Description
Flag
-d --delimiter use charater of TAB
paste one file at a time instead of in
-s --serial
parallel
-z --zero-terminated set line delimiter to NUL, not newline
207
Short
Long Flag Description
Flag
--help print command help
--version print version information
208
The exit command
Syntax:
exit
209
The diff/sdiff command
Syntax:
Example
1. Lets say we have two files with names a.txt and b.txt containing 5
Indian states as follows-:
$ cat a.txt
Gujarat
Uttar Pradesh
Kolkata
Bihar
Jammu and Kashmir
$ cat b.txt
Tamil Nadu
Gujarat
Andhra Pradesh
Bihar
Uttar pradesh
210
$ diff a.txt b.txt
0a1
> Tamil Nadu
2,3c3
< Uttar Pradesh
Andhra Pradesh
5c5
Uttar pradesh
211
The tar command
The tar command stands for tape archive, is used to create Archive
and extract the Archive files. This command provides archiving
functionality in Linux. We can use tar command to create compressed
or uncompressed Archive files and also maintain and modify them.
Examples:
Syntax:
212
Use Flag Description
-t Displays or lists files in archived file
-u Archives and adds to an existing archive file
-v Displays Verbose Information
-A Concatenates the archive files
-z zip, tells tar command that creates tar file using gzip
-j Filter archive tar file using tbzip
w Verify a archive file
update or add file or directory in already existed .tar
r
file
-? Displays a short summary of the project
Find the difference between an archive and file
-d
system
--usage shows available tar options
--version Displays the installed tar version
--show-defaults Shows default enabled options
Option Flag Description
Check device numbers during
--check-device
incremental archive
Used to allow compatibility with GNU-
-g
format incremental ackups
Used to detect holes in the sparse
--hole-detection
files
Used to allow compatibility with old
-G
GNU-format incremental backups
Don't exit the program on file read
--ignore-failed-read
errors
Set the dump level for created
--level
archives
-n Assume the archive is seekable
Do not check device numbers when
--no-check-device
creating archives
--no-seek Assume the archive is not seekable
`Process only the Nth occurrence of
--occurrence=N
each file
213
Option Flag Description
`Disable use of potentially harmful
--restrict
options
Set version of the sparce format to
--sparse-version=MAJOR,MINOR
use
-S Handle sparse files efficiently.
Overwright control Flag Description
-k Don't replace existing files
Don't replace existing files that are newer
--keep-newer-files
than the archives version
--keep-directory-symlink Don't replace existing symlinks
--no-overwrite-dir Preserve metadata of existing directories
--one-top-level=DIR Extract all files into a DIR
--overwrite Overwrite existing files
--overwrite-dir Overwrite metadata of directories
Recursivly remove all files in the directory
--recursive-unlink
before extracting
Remove files after adding them to a
--remove-files
directory
Don't replace existing files when
--skip-old-files
extracting
-u Remove each file before extracting over it
-w Verify the archive after writing it
214
The gunzip command
gunzip takes a list of files on its command line and replaces each file
whose name ends with .gz, -gz, .z, -z, or _z (ignoring case) and which
begins with the correct magic number with an uncompressed file
without the original extension. gunzip also recognizes the special
extensions .tgz and .taz as shorthands for .tar.gz and .tar.Z
respectively.
Examples:
1. Uncompress a file
gunzip filename.gz
gunzip -r directory_name/
gunzip -S .tgz *
215
4. List compressed and uncompressed sizes, compression ratio and
uncompressed name of input compressed file/s:
Syntax:
Short
Long Flag Description
Flag
write on standard output, keep original files
-c --stdout
unchanged
-h --help give help information
-k --keep keep (don't delete) input files
-l --list list compressed file contents
-q --quiet suppress all warnings
-r --recursive operate recursively on directories
-S --suffix=SUF use suffix SUF on compressed files
synchronous output (safer if system crashes,
--synchronous
but slower)
-t --test test compressed file integrity
-v --verbose verbose mode
216
Short
Long Flag Description
Flag
-V --version display version number
217
The hostnamectl command
218
Syntax
219
Example
$ hostnamectl
or
$ hostnamectl status
220
The iptables Command
The iptables command is used to set up and maintain tables for the
Netfilter firewall for IPv4, included in the Linux kernel. The firewall
matches packets with rules defined in these tables and then takes the
specified action on a possible match.
Syntax:
Flag Description
Check if a rule is present in the chain or not. It returns 0 if the
-C
rule exists and returns 1 if it does not.
-A Append to the chain provided in parameters.
221
The netstat command
netstat –v
If you don't have netstat installed on your PC, you can install it with
the following command:
You can use netstat command for some use cases given
below:
Netstat command with -nr flag shows the routing table detail on
the terminal.
Example:
netstat -nr
222
Example:
netstat -i
Example:
netstat -tunlp
You can get the list of all TCP port connection by using -at with
netstat.
netstat -at
You can get the list of all UDP port connection by using -au with
netstat.
netstat -au
You can get the list of all active connection by using -l with
netstat.
netstat -l
223
The lsof command
The lsof command shows file infomation of all the files opened by a
running process. It's name is also derived from the fact that, list open
files > lsof
Syntax:
Examples:
lsof
lsof -u [USER_NAME]
224
lsof +d [PATH_TO_DIR]
Help Command
man lsof
225
The bzip2 command
The bzip2 command lets you compress and decompress the files i.e. it
helps in binding the files into a single file which takes less storage
space as the original file use to take.
Syntax:
226
Option Alias Description
to enable file compression, but deletes the
-z --compress
original input file
Examples:
1. To force compression:
bzip2 -z input.txt
bzip2 -k input.txt
3. To force decompression:
bzip2 -d input.txt.bz2
bzip2 -t input.txt.bz2
227
bzip2 -v input.txt
228
The service command
service --status-all runs all init scripts, in alphabetical order, with the
status command
Examples :
service --status-all
2. To run a script
229
service [SCRIPT] [COMMAND] [OPTIONS]
230
The vmstat command
The vmstat command lets you monitor the performance of your system.
It shows you information about your memory, disk, processes, CPU
scheduling, paging, and block IO. This command is also referred to as
virtual memory statistic report.
The very first report that is produced shows you the average details
since the last reboot and after that, other reports are made which
report over time.
vmstat
As you can see it is a pretty useful little command. The most important
things that we see above are the free, which shows us the free space
that is not being used, si shows us how much memory is swapped in
every second in kB, and so shows how much memory is swapped out
each second in kB as well.
vmstat -a
If we run vmstat -a, it will show us the active and inactive memory of
the system running.
vmstat -d
231
As you can see this is a pretty useful little command that shows you
different statistics about your virtual memory
232
The mpstat command
Syntax:
Option Description
-A to display all the detailed statistics
-h to display mpstat help
-I to display detailed interrupts statistics
to report summary CPU statistics based on NUMA node
-n
placement
to indicate the NUMA nodes for which statistics are to be
-N
reported
to indicate the processors for which statistics are to be
-P
reported
to display the statistics in JSON (Javascript Object Notation)
-o
format
-T to display topology elements in the CPU report
-u to report CPU utilization
-v to display utilization statistics at the virtual processor level
233
Option Description
-V to display mpstat version
-ALL to display detailed statistics about all CPUs
Examples:
mpstat
mpstat -P ALL
mpstat -A
mpstat -P 0
mpstat 1 5
234
The ncdu Command
235
Example
1. Quiet Mode
ncdu -q
ncdu -q -x
236
Syntax
237
Additional Flags and their Functionalities:
Short
Long Flag Description
Flag
-h - Print a small help message
Quiet mode. While calculating disk space,
ncdu will update the screen 10 times a
second by default, this will be decreased
-q -
to once every 2 seconds in quiet mode.
Use this feature to save bandwidth over
remote connections.
-v - Print version.
Only count files and directories on the
-x -
same filesystem as the specified dir.
Exclude files that match PATTERN. This
--exclude
- PATTERN
argument can be added multiple times to
add more patterns.
Exclude files that match any pattern in
-X --exclude-from
FILE FILE
FILE. Patterns should be separated by a
newline.
238
The uniq command
Examples:
In order to omit the repeated lines from a file, the syntax would be the
following:
uniq kt.txt
In order to tell the number of times a line was repeated, the syntax
would be the following:
uniq -c kt.txt
uniq -d kt.txt
239
uniq -u kt.txt
uniq -f 2 kt.txt
uniq -s 5 kt.txt
uniq -i kt.txt
Syntax:
Possible options:
240
Flag Description Params
By default, comparisons done are case sensitive
-i but with this option case insensitive comparisons -
can be made.
It allows you to skip N fields(a field is a group of
-f characters, delimited by whitespace) of a line N
before determining uniqueness of a line.
It doesn’t compares the first N characters of each
line while determining uniqueness. This is like the
-s N
-f option, but it skips individual characters rather
than fields.
-u It allows you to print only unique lines. -
It will make a line end with 0 byte(NULL), instead
-z -
of a newline.
-w It only compares N characters in a line. N
--help It displays a help message and exit. -
--version It displays version information and exit. -
241
The RPM command
General Options
Short
Long Flag Description
Flag
-? --help Print a longer usage message then normal.
Print a single line containing the version number of rpm being
- --version
used.
Print as little as possible - normally only error messages will be
- --quiet
displayed.
Print verbose information - normally routine progress messages
-v -
will be displayed.
-vv - Print lots of ugly debugging information.
242
Short
Long Flag Description
Flag
Each of the files in the colon separated FILELIST is read
sequentially by rpm for configuration information. Only the first
- --rcfile FILELIST file in the list must exist, and tildes will be expanded to the value
of $HOME. The default FILELIST is
/usr/lib/rpm/rpmrc:/usr/lib/rpm/redhat/rpmrc:/etc/rpmrc:~/.rpmrc.
- --pipe CMD Pipes the output of rpm to the command CMD.
--dbpath Use the database in DIRECTORY rather than the default path
-
DIRECTORY /var/lib/rpm
Use the file system tree rooted at DIRECTORY for all operations.
Note that this means the database within DIRECTORY will be
--root
- used for dependency checks and any scriptlet(s) (e.g. %post if
DIRECTORY
installing, or %prep if building, a package) will be run after a
chroot(2) to DIRECTORY.
--define='MACRO
-D Defines MACRO with value EXPR.
EXPR'
-E --eval='EXPR' Prints macro expansion of EXPR.
243
Synopsis
244
Querying and Verifying Packages:
245
Installing, Upgrading, and Removing Packages:
246
Miscellaneous:
rpm {--initdb|--rebuilddb}
rpm {--querytags|--showrc}
query-options
verify-options
install-options
247
[--aid] [--allfiles] [--badreloc] [--excludepath OLDPATH]
[--excludedocs] [--force] [-h,--hash]
[--ignoresize] [--ignorearch] [--ignoreos]
[--includedocs] [--justdb] [--nodeps]
[--nodigest] [--nosignature] [--nosuggest]
[--noorder] [--noscripts] [--notriggers]
[--oldpackage] [--percent] [--prefix NEWPATH]
[--relocate OLDPATH=NEWPATH]
[--replacefiles] [--replacepkgs]
[--test]
248
The scp command
Both the files and passwords are encrypted so that anyone snooping on
the traffic doesn't get anything sensitive.
Examples:
scp root@{remote-ip-address}:/home/remote-file
/home/documents/
3. To copy the files between two remote systems from the local
system.
249
scp root@{remote1-ip-address}:/home/remote-file root@{remote2-
ip-address}/home/
On newer version of scp on some machines you can use the above
command with a -J flag.
Syntax:
scp provides several that control every aspect of its behaviour. The
most widely used options are:
Short Long
Description
Flag Flag
-P - Specifies the remote host ssh port.
250
Short Long
Description
Flag Flag
-p - Preserves files modification and access times.
Use this option if you want to suppress the progress
-q -
meter and non-error messages.
This option forces scp to compresses the data as it
-C -
is sent to the destination machine.
-r - This option tells scp to copy directories recursively.
The scp command relies on ssh for data transfer, so it requires an ssh
key or password to authenticate on the remote systems.
The colon (:) is how scp distinguish between local and remote
locations.
To be able to copy files, you must have at least read permissions on the
source file and write permission on the target system.
Be careful when copying files that share the same name and location on
both systems, scp will overwrite files without warning.
251
The sleep command
The sleep command is used to create a dummy job. A dummy job helps
in delaying the execution. It takes time in seconds by default but a
small suffix(s, m, h, d) can be added at the end to convert it into any
other format. This command pauses the execution for an amount of
time which is defined by NUMBER.
Note: If you will define more than one NUMBER with sleep command
then this command will delay for the sum of the values.
Examples :
sleep 10s
sleep NUMBER[SUFFIX]...
252
Options
1. --help
display this help and exit
2. --version
output version information and exit
253
The split command
The split command in Linux is used to split a file into smaller files.
Examples
split filename.txt
This will create files of the name fileaa, fileab, fileac, filead, etc. of 200
lines.
This will create files of the name fileaa, fileab, fileac, filead, etc. of 40
bytes.
254
split filename.txt --verbose
Syntax:
Short
Long Flag Description
Flag
Generate suffixes of length N
-a --suffix-length=N
(default 2)
Append an additional SUFFIX to
--additional-suffix=SUFFIX
file names
-b --bytes=SIZE Put SIZE bytes per output file
Put at most SIZE bytes of
-C --line-bytes=SIZE
records per output file
Use numeric suffixes starting at
-d
0, not alphabetic
Same as -d, but allow setting
--numeric-suffixes[=FROM]
the start value
Use hex suffixes starting at 0,
-x
not alphabetic
Same as -x, but allow setting
--hex-suffixes[=FROM]
the start value
Do not generate empty output
-e --elide-empty-files
files with '-n'
Write to shell COMMAND;
--filter=COMMAND
file name is $FILE
Put NUMBER lines/records per
-l --lines=NUMBER
output file
Generate CHUNKS output files;
-n --number=CHUNKS
see explanation below
255
Short
Long Flag Description
Flag
Use SEP instead of newline as
the record separator;
-t --separator=SEP
'\0' (zero) specifies the NUL
character
Immediately copy input to
-u --unbuffered
output with '-n r/...'
Print a diagnostic just before
--verbose each
output file is opened
--help Display this help and exit
Output version information and
--version
exit
CHUNKS Description
N Split into N files based on size of input
K/N Output Kth of N to stdout
l/N Split into N files without splitting lines/records
l/K/N Output Kth of N to stdout without splitting lines/records
r/N Like 'l' but use round robin distribution
r/K/N Likewise but only output Kth of N to stdout
256
The stat command
The stat command lets you display file or file system status. It gives
you useful information about the file (or directory) on which you use it.
Examples:
stat file.txt
stat file.txt -c %s
Syntax:
Short
Long Flag Description
Flag
-L --dereference Follow links
Display file system status instead of file
-f --file-system
status
257
Short
Long Flag Description
Flag
-c --format=FORMAT Specify the format (see below)
-t --terse Print the information in terse form
Specify how to use cached attributes. Can
- --cached=MODE
be: always, never, or default
Like --format, but interpret backslash
- --printf=FORMAT
escapes (\n, \t, ...)
- --help Display the help and exit
- --version Output version information and exit
Format Description
%a Permission bits in octal
%A Permission bits and file type in human readable form
%d Device number in decimal
%D Device number in hex
%F File type
%g Group ID of owner
%G Group name of owner
%h Number of hard links
%i Inode number
%m Mount point
%n File name
%N Quoted file name with dereference if symbolic link
%s Total size, in bytes
%u User ID of owner
%U User name of owner
%w Time of file birth, human-readable; - if unknown
%x Time of last access, human-readable
%y Time of last data modification, human-readable
%z Time of last status change, human-readable
258
The useradd command
Examples:
To add a new user with the useradd command the syntax would be the
following:
useradd NewUser
To add a new user with the useradd command and give a home
directory path for this new user the syntax would be the following:
To add a new user with the useradd command and give it a specific id
the syntax would be the following:
Syntax:
259
Possible options:
260
The userdel command
Examples:
To delete a user with the userdel command the syntax would be the
following:
userdel userName
To force the removal of a user account even if the user is still logged in,
using the userdel command the syntax would be the following:
userdel -f userName
To delete a user along with the files in the user’s home directory using
the userdel command the syntax would be the following:
userdel -r userName
Syntax:
261
Possible options:
Flag Description
Force the removal of the specified user account even if the user
-f
is logged in
Remove the files in the user’s home directory along with the
-r
home directory itself and the user’s mail spool
Remove any SELinux(Security-Enhanced Linux) user mapping for
-Z
the user’s login.
262
The usermod command
The usermod command lets you change the properties of a user in Linux
through the command line. After creating a user we sometimes have to
change their attributes, like their password or login directory etc. So in
order to do that we use the usermod command.
Syntax:
Option Description
-a to add anyone of the group to a secondary group
-c to add comment field for the useraccount
-d to modify the directory for any existing user account
-g change the primary group for a User
-G to add supplementary groups
-l to change existing user login name
-L to lock system user account
to move the contents of the home directory from existing
-m
home dir to new dir
-p to create an un-encrypted password
-s to create a specified shell for new accounts
-u to assigned UID for the user account
263
Option Description
-U to unlock any locked user
Examples:
6. To lock a user:
7. To unlock a user:
264
sudo usermod -U test_user
265
The ionice command
The ionice command is used to set or get process I/O scheduling class
and priority.
If no arguments are given , ionice will query the current I/O scheduling
class and priority for that process.
266
Usage
267
A process can be of three scheduling classes:
Idle
A program with idle I/O priority will only get disk time when no
other program has asked for disk I/O for a defined grace
period.
Best Effort
This is effective scheduling class for any process that has not
asked for a specific I/O priority.
Note that before kernel 2.6.26 a process that has not asked for an
I/O priority formally uses “None” as scheduling class , but the io
schedular will treat such processes as if it were in the best effort
class.
268
form the CPU nice level of the process : io_priority = ( cpu_nice +
20 ) / 5/ for kernels after 2.6.26 with CFQ I/O schedular a process
that has not asked for sn io priority inherits CPU scheduling class.
Real Time
Thus the real time class needs to be used with some care, as it
cans tarve other processes .
269
Options
Options Description
name or number of scheduling class, 0: none, 1:
-c, --class
realtime, 2: best-effort, 3: idle
priority (0..7) in the specified scheduling class,only for
-n, --classdata
the realtime and best-effort classes
-p, --pid ... act on these already running processes
-P, --pgid ... act on already running processes in these groups
-t, --ignore ignore failures
-u, --uid ... act on already running processes owned by these users
-h, --help display this help
-V, --version display version
270
Examples
271
Conclusion
272
The du command
The du command, which is short for disk usage lets you retrieve
information about disk space usage information in a specified directory.
In order to customize the output according to the information you need,
this command can be paired with the appropriate options or flags.
Examples:
du
du {PATH_TO_DIRECTORY}
Syntax:
du [OPTION]... [FILE]...
du [OPTION]... --files0-from=F
273
Short
Long Flag Description
Flag
Includes information for both files and
-a --all
directories
Provides a grand total at the end of the
-c --total
list of files/directories
Provides information up to N levels from
-d --max-depth=N the directory where the command was
executed
Displays file size in human-readable units,
-h --human-readable
not in bytes
Display only the total filesize instead of a
-s --summarize
list of files/directories
274
The ping command
275
Understanding Latency
When you use the ping command, it measures the latency by sending a
series of packets to the target host and calculating the time it takes for
each packet to complete the round trip. The latency is typically
measured in milliseconds (ms). Understanding latency is essential
because:
Examples:
276
sudo ping -v
ping google.com
ping -c 5 google.com
ping -s 40 -c 5 google.com
ping -i 2 google.com
277
The rsync command
The rsync command is probably one of the most used commands out
there. It is used to securely copy files from one server to another over
SSH.
In this tutorial, I will show you how to use the rsync command and copy
files from one server to another and also share a few useful tips!
Before you get started, you would need to have 2 Linux servers. I will
be using DigitalOcean for the demo and deploy 2 Ubuntu servers.
You can use my referral link to get a free $100 credit that you could use
to deploy your virtual machines and test the guide yourself on a few
DigitalOcean servers:
278
Transfer Files from local server to remote
This is one of the most common causes. Essentially this is how you
would copy the files from the server that you are currently on (the
source server) to remote/destination server.
What you need to do is SSH to the server that is holding your files, cd to
the directory that you would like to transfer over:
cd /var/www/html
The above command would copy all the files and directories from the
current folder on your server to your remote server.
-a: is used to specify that you want recursion and want to preserve
the file permissions and etc.
-v: is verbose mode, it increases the amount of information you
are given during the transfer.
-z: this option, rsync compresses the file data as it is sent to the
destination machine, which reduces the amount of data being
transmitted -- something that is useful over a slow connection.
https://explainshell.com/explain?cmd=rsync+-avz
279
In case that the SSH service on the remote server is not running on the
standard 22 port, you could use rsync with a special SSH port:
280
Transfer Files remote server to local
In some cases you might want to transfer files from your remote server
to your local server, in this case, you would need to use the following
syntax:
Again, in case that you have a non-standard SSH port, you can use the
following command:
281
Transfer only missing files
If you would like to transfer only the missing files you could use the --
ignore-existing flag.
This is very useful for final sync in order to ensure that there are no
missing files after a website or a server migration.
Basically the commands would be the same apart from the appended --
ignore-existing flag:
282
Conclusion
Using rsync is a great way to quickly transfer some files from one
machine over to another in a secure way over SSH.
For more cool Linux networking tools, I would recommend checking out
this tutorial here:
Initially posted here: How to Transfer Files from One Linux Server to
Another Using rsync
283
The dig command
Examples:
dig google.com
2. The system will list all google.com DNS records that it finds, along
with the IP addresses.
Syntax:
284
Additional Flags and their Functionalities:
285
authority section)
+[no]badcookie (Retry BADCOOKIE
responses)
+[no]besteffort (Try to parse even
illegal messages)
+bufsize[=###] (Set EDNS0 Max UDP packet
size)
+[no]cdflag (Set checking disabled
flag in query)
+[no]class (Control display of class
in records)
+[no]cmd (Control display of
command line -
global option)
+[no]comments (Control display of
packet header
and section name
comments)
+[no]cookie (Add a COOKIE option to
the request)
+[no]crypto (Control display of
cryptographic
fields in records)
+[no]defname (Use search list
(+[no]search))
+[no]dnssec (Request DNSSEC records)
+domain=### (Set default domainname)
+[no]dscp[=###] (Set the DSCP value to
### [0..63])
+[no]edns[=###] (Set EDNS version) [0]
+ednsflags=### (Set EDNS flag bits)
+[no]ednsnegotiation (Set EDNS version
negotiation)
+ednsopt=###[:value] (Send specified EDNS
option)
+noednsopt (Clear list of +ednsopt
options)
+[no]expandaaaa (Expand AAAA records)
+[no]expire (Request time to expire)
+[no]fail (Don't try next server on
SERVFAIL)
+[no]header-only (Send query without a
question section)
+[no]identify (ID responders in short
answers)
+[no]idnin (Parse IDN names
286
[default=on on tty])
+[no]idnout (Convert IDN response
[default=on on tty])
+[no]ignore (Don't revert to TCP for
TC responses.)
+[no]keepalive (Request EDNS TCP
keepalive)
+[no]keepopen (Keep the TCP socket open
between queries)
+[no]mapped (Allow mapped IPv4 over
IPv6)
+[no]multiline (Print records in an
expanded format)
+ndots=### (Set search NDOTS value)
+[no]nsid (Request Name Server ID)
+[no]nssearch (Search all authoritative
nameservers)
+[no]onesoa (AXFR prints only one soa
record)
+[no]opcode=### (Set the opcode of the
request)
+padding=### (Set padding block size
[0])
+[no]qr (Print question before
sending)
+[no]question (Control display of
question section)
+[no]raflag (Set RA flag in query
(+[no]raflag))
+[no]rdflag (Recursive mode
(+[no]recurse))
+[no]recurse (Recursive mode
(+[no]rdflag))
+retry=### (Set number of UDP
retries) [2]
+[no]rrcomments (Control display of per-
record comments)
+[no]search (Set whether to use
searchlist)
+[no]short (Display nothing except
short
form of answers - global
option)
+[no]showsearch (Search with intermediate
results)
+[no]split=## (Split hex/base64 fields
287
into chunks)
+[no]stats (Control display of
statistics)
+subnet=addr (Set edns-client-subnet
option)
+[no]tcflag (Set TC flag in query
(+[no]tcflag))
+[no]tcp (TCP mode (+[no]vc))
+timeout=### (Set query timeout) [5]
+[no]trace (Trace delegation down
from root [+dnssec])
+tries=### (Set number of UDP
attempts) [3]
+[no]ttlid (Control display of ttls
in records)
+[no]ttlunits (Display TTLs in human-
readable units)
+[no]unexpected (Print replies from
unexpected sources
default=off)
+[no]unknownformat (Print RDATA in RFC 3597
"unknown" format)
+[no]vc (TCP mode (+[no]tcp))
+[no]yaml (Present the results as
YAML)
+[no]zflag (Set Z flag in query)
global d-opts and servers (before host name) affect
all queries.
local d-opts and servers (after host name) affect only
that lookup.
-h (print help and exit)
-v (print version and exit)
288
The whois command
Examples:
whois {Domain_name}
whois -H {Domain_name}
Syntax:
whois -t TYPE
289
whois -v TYPE
whois -q keyword
Flag Description
-h HOST, --host HOST Connect to HOST.
Do not display the legal disclaimers some
-H
registries like to show you.
-p, --port PORT Connect to PORT.
--verbose Be verbose.
--help Display online help.
Display client version information. Other
options are flags understood by
--version
whois.ripe.net and some other RIPE-like
servers.
-a Also search all the mirrored databases.
Return brief IP address ranges with abuse
-b
contact.
Disable object filtering (show the e-mail
-B
addresses)
Return the smallest IP address range with a
-c
reference to an irt object.
Return the reverse DNS delegation object
-d
too.
Search updates from SOURCE database
between FIRST and LAST update serial
-g SOURCE:FIRST-LAST
number. It's useful to obtain Near Real Time
Mirroring stream.
-G Disable grouping of associated objects.
Search objects having associated attributes.
-i ATTR[,ATTR]... ATTR is attribute name. Attribute value is
positional OBJECT argument.
290
Flag Description
Return primary key attributes only. Exception
is members attribute of set object which is
-K always returned. Another exceptions are all
attributes of objects organisation, person,
and role that are never returned.
-l Return the one level less specific object.
-L Return all levels of less specific objects.
-m Return all one level more specific objects.
-M Return all levels of more specific objects.
Return list of keywords supported by server.
KEYWORD can be version for server version,
-q KEYWORD
sources for list of source databases, or types
for object types.
Disable recursive look-up for contact
-r
information.
Disable following referrals and force showing
-R
the object from the local copy in the server.
Request the server to search for objects
mirrored from SOURCES. Sources are
-s SOURCE[,SOURCE]... delimited by comma and the order is
significant. Use -q sources option to obtain
list of valid sources.
-t TYPE Return the template for a object of TYPE.
Restrict the search to objects of TYPE.
-T TYPE[,TYPE]...
Multiple types are separated by a comma.
Return the verbose template for a object of
-v TYPE
TYPE.
Search for only exact match on network
-x
address prefix.
291
The ssh command
Examples:
Syntax:
ssh user_name@host(IP/Domain_Name)
292
ssh -i private.key user_name@host
Flag Description
Forces ssh to use protocol
-1
SSH-1 only.
Forces ssh to use protocol
-2
SSH-2 only.
-4 Allows IPv4 addresses only.
Authentication agent
-A connection forwarding is
enabled..
Authentication agent
-a connection forwarding is
disabled.
Bind to the address of
bind_interface before
attempting to connect to the
-B bind_interface
destination host. This is only
useful on systems with more
than one address.
Use bind_address on the
local machine as the source
-b bind_address address of the connection.
Only useful on systems with
more than one address.
Compresses all data
(including stdin, stdout,
stderr, and data for
-C
forwarded X11 and TCP
connections) for a faster
transfer of data.
293
Flag Description
Selects the cipher
-c cipher_spec specification for encrypting
the session.
Dynamic application-level
port forwarding. This
allocates a socket to listen to
port on the local side. When
a connection is made to this
-D [bind_address:]port port, the connection is
forwarded over the secure
channel, and the application
protocol is then used to
determine where to connect
to from the remote machine.
Append debug logs instead
-E log_file
of standard error.
Sets the escape character for
sessions with a pty (default:
‘~’). The escape character is
only recognized at the
beginning of a line. The
escape character followed by
a dot (‘.’) closes the
-e escape_char connection; followed by
control-Z suspends the
connection; and followed by
itself sends the escape
character once. Setting the
character to “none” disables
any escapes and makes the
session fully transparent.
Specifies a per-user
configuration file. The default
-F configfile
for the per-user configuration
file is ~/.ssh/config.
Requests ssh to go to
-f background just before
command execution.
294
Flag Description
Causes ssh to print its
configuration after
-G
evaluating Host and Match
blocks and exit.
Allows remote hosts to
-g connect to local forwarded
ports.
Specify the PKCS#11 shared
library ssh should use to
-I pkcs11 communicate with a
PKCS#11 token providing
keys.
A file from which the identity
-i identity_file key (private key) for public
key authentication is read.
Connect to the target host by
first making a ssh connection
to the pjump
-J [user@]host[:port] host[(/iam/jump-host) and
then establishing a TCP
forwarding to the ultimate
destination from there.
Enables GSSAPI-based
authentication and
-K forwarding (delegation) of
GSSAPI credentials to the
server.
Disables forwarding
-k (delegation) of GSSAPI
credentials to the server.
295
Flag Description
Specifies that connections to
the given TCP port or Unix
socket on the local (client)
host are to be forwarded to
the given host and port, or
Unix socket, on the remote
side. This works by allocating
-L a socket to listen to either a
[bind_address:]port:host:hostport, TCP port on the local side,
-L optionally bound to the
[bind_address:]port:remote_socket, specified bind_address, or to
-L local_socket:host:hostport, -L a Unix socket. Whenever a
local_socket:remote_socket connection is made to the
local port or socket, the
connection is forwarded over
the secure channel, and a
connection is made to either
host port hostport, or the
Unix socket remote_socket,
from the remote machine.
Specifies the user to log in as
-l login_name
on the remote machine.
Places the ssh client into
“master” mode for
connection sharing. Multiple -
M options places ssh into
“master” mode but with
-M
confirmation required using
ssh-askpass before each
operation that changes the
multiplexing state (e.g.
opening a new session).
A comma-separated list of
MAC (message
-m mac_spec authentication code)
algorithms, specified in order
of preference.
Do not execute a remote
-N command. This is useful for
just forwarding ports.
296
Flag Description
-n Prevents reading from stdin.
Control an active connection
multiplexing master process.
When the -O option is
specified, the ctl_cmd
argument is interpreted and
passed to the master
process. Valid commands
are: “check” (check that the
master process is running),
-O ctl_cmd
“forward” (request
forwardings without
command execution),
“cancel” (cancel
forwardings), “exit” (request
the master to exit), and
“stop” (request the master to
stop accepting further
multiplexing requests).
Can be used to give options
in the format used in the
configuration file. This is
-o
useful for specifying options
for which there is no
separate command-line flag.
Port to connect to on the
-p, --port PORT
remote host.
297
Flag Description
Queries ssh for the
algorithms supported for the
specified version 2. The
available features are: cipher
(supported symmetric
ciphers), cipher-auth
(supported symmetric
ciphers that support
authenticated encryption),
help (supported query terms
for use with the -Q flag), mac
(supported message integrity
codes), kex (key exchange
algorithms), kex-gss (GSSAPI
key exchange algorithms),
-Q query_option
key (keytypes), key-cert
(certificate key types), key-
plain (non-certificate key
types), key-sig (all keytypes
and signature algorithms),
protocol-version (supported
SSH protocol versions), and
sig (supported signature
algorithms). Alternatively,
any keyword from
ssh_config(5) or
sshd_config(5) thattakes an
algorithm list may be used as
an alias for the
corresponding query_option.
Qiet mode. Causes most
-q warning and diagnostic
messages to be suppressed.
-R
[bind_address:]port:host:hostport, Specifies that connections to
-R the given TCP port or Unix
[bind_address:]port:local_socket, socket on the remote
-R remote_socket:host:hostport, -R (server) host are to be
remote_socket:local_socket, -R forwarded to the local side.
[bind_address:]port
298
Flag Description
Specifies the location of a
control socket for connection
-S ctl_path sharing, or the string “none”
to disable connection
sharing.
May be used to request
invocation of a subsystem on
the remote system.
Subsystems facilitate the use
-s of SSH as a secure transport
for other applications (e.g.
sftp(1)). The subsystem is
specified as the remote
command.
Disable pseudo-terminal
-T
allocation.
Force pseudo-terminal
allocation. This can be used
to execute arbitrary screen-
based programs on a remote
machine, which can be very
-t
useful, e.g. when
implementing menu services.
Multiple -t options force tty
allocation, even if ssh has no
local tty.
-V Display the version number.
Verbose mode. It echoes
everything it is doing while
establishing a connection. It
-v
is very useful in the
debugging of connection
failures.
299
Flag Description
Requests that standard input
and output on the client be
forwarded to host on port
over the secure channel.
Implies -N, -T,
-W host:port
ExitOnForwardFailure and
ClearAllForwardings, though
these can be overridden in
the configuration file or using
-o command line options.
Requests tunnel device
forwarding with the specified
tun devices between the
client (local_tun) and the
server (remote_tun). The
devices may be specified by
numerical ID or the keyword
“any”, which uses the next
available tunnel device. If
-w local_tun[remote_tun]
remote_tun is not specified,
it defaults to “any”. If the
Tunnel directive is unset, it
will be set to the default
tunnel mode, which is “point-
to-point”. If a different
Tunnel forwarding mode it
desired, then it should be
specified before -w.
Enables X11 forwarding (GUI
-X
Forwarding).
Disables X11 forwarding (GUI
-x
Forwarding).
Enables trusted X11
-Y
Forwarding.
Send log information using
the syslog system module.
-y
By default this information is
sent to stderr.
300
The awk command
1. AWK Operations: (a) Scans a file line by line (b) Splits each input
line into fields (c) Compares input line/fields to pattern (d)
Performs action(s) on matched lines
2. Useful For: (a) Transform data files (b) Produce formatted reports
Syntax
Example
Consider the following text file as the input file for below example:
301
```
$cat > employee.txt
```
```
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
```
302
In the above example, the awk command prints all the line which
matches with the ‘manager’.
3. Splitting a Line Into Fields : For each record i.e line, the awk
command splits the record delimited by whitespace character by
default and stores it in the $n variables. If the line has 4 words, it
will be stored in $1, $2, $3 and $4 respectively. Also, $0 represents
the whole line.
ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
Awk’s built-in variables include the field variables—$1, $2, $3, and so
on ($0 is the entire line) — that break a line of text into individual words
or pieces called fields.
303
separator, which separates the fields when Awk prints them. The
default is a blank space. Whenever print has several parameters
separated with commas, it will print the value of OFS in between each
parameter. ORS: ORS command stores the output record separator,
which separates the output lines when Awk prints them. The default is a
newline character. print automatically outputs the contents of ORS at
the end of whatever it is given to print.
304
The crontab command
crontab is the program used to install, uninstall or list the tables used to
drive the cron(8) daemon in Vixie Cron. Each user can have their own
crontab, and though these are files in /var/spool/cron/crontabs, they
are not intended to be edited directly.
Syntax:
Examples:
crontab -l
crontab -r
3. The -e option is used to edit the current crontab using the editor
specified by the VISUAL or EDITOR environment variables. After
305
you exit from the editor, the modified crontab will be installed
automatically. If neither of the environment variables is defined,
then the default editor /usr/bin/editor is used.
crontab -e
4. You can specify the user you want to edit the crontab for. Every
user has its own crontab. Assume you have a www-data user, which
is in fact the user Apache is default running as. If you want to edit
the crontab for this user you can run the following command
crontab -u www-data -e
Help Command
man crontab
306
The xargs command
xargs is used to build and execute command lines from standard input
Some commands like grep can accept input as parameters, but some
commands accepts arguments, this is place where xargs came into
picture.
Syntax:
Options:
-0, --null
-a file, --arg-file=file
Read items from file instead of standard input. If you use this option,
stdin remains unchanged when commands are run. Otherwise, stdin is
redirected from /dev/null.
307
-o, --open-tty
--delimiter=delim, -d delim
-p, --interactive
Prompt the user about whether to run each command line and read a
line from the terminal. Only run the command line if the response starts
with y' or Y'. Implies -t.
Examples:
Find files named core in or below the directory /tmp and delete them.
308
Note that this will work incorrectly if there are any filenames containing
newlines or spaces.
Find files named core in or below the directory /tmp and delete them,
processing filenames in such a way that file or directory names
containing spaces or new‐ lines are correctly handled.
Find files named core in or below the directory /tmp and delete them,
but more efficiently than in the previous example (because we avoid
the need to use fork(2) and exec(2) to launch rm and we don't need the
extra xargs process).
Help Command
man xargs
309
The nohup command
When a shell exits (maybe while logging out of an SSH session), the
HUP ('hang up') signal is send to all of its child processes, causing them
to terminate. If you require a long-running process to continue after
exiting shell, you'll need the nohup command. Prefixing any command
with nohup causes the command to become immune to HUP signals.
Additionally, STDIN is being ignored and all output gets redirected to
local file ./nohup.out.
Examples:
Syntax:
310
The pstree command
The pstree command is similar to ps, but instead of listing the running
processes, it shows them as a tree. The tree-like format is sometimes
more suitable way to display the processes hierarchy which is a much
simpler way to visualize running processes. The root of the tree is either
init or the process with the given pid.
Examples
pstree
2. To display a tree with the given process as the root of the tree:
pstree [pid]
pstree [USER]
pstree -s [PID]
311
command:
pstree | less
Syntax
Short
Long Flag Description
Flag
-a --arguments Show command line arguments
-A --ascii use ASCII line drawing characters
-c --compact Don't compact identical subtrees
Highlight current process and its
-h --highlight-all
ancestors
highlight this process and its
-H PID --highlight-pid=PID
ancestors
-g --show-pgids show process group ids; implies -c
-G --vt100 use VT100 line drawing characters
-l --long Don't truncate long lines
-n --numeric-sort Sort output by PID
Sort by namespace type (cgroup, ipc,
-N type --ns-sort=type
mnt, net, pid, user, uts)
-p --show-pids show PIDs; implies -c
-s --show-parents Show parents of the selected process
-S --ns-changes show namespace transitions
-t --thread-names Show full thread names
-T --hide-threads Hide threads, show only processes
-u --uid-changes Show uid transitions
Use UTF-8 (Unicode) line drawing
-U --unicode
characters
312
Short
Long Flag Description
Flag
-V --version Display version information
-Z --security-context Show SELinux security contexts
313
The tree command
Examples:
tree
tree -L 2 /
Syntax:
314
Additional Flags and their Functionalities:
Flag Description
-a Print all files, including hidden ones.
-d Only list directories.
-l Follow symbolic links into directories.
Print the full path to each listing, not just its
-f
basename.
-x Do not move across file-systems.
-L # Limit recursion depth to #.
-P REGEX Recurse, but only list files that match the REGEX.
-I REGEX Recurse, but do not list files that match the REGEX.
--ignore-case Ignore case while pattern-matching.
--prune Prune empty directories from output.
--filelimit # Omit directories that contain more than # files.
-o FILE Redirect STDOUT output to FILE.
-i Do not output indentation.
315
The whereis command
Syntax
Options
316
said to be unusual if it does not have any existence in system as per [-
bmsu] described along with “–u”. Thus `whereis -m -u *‘ asks for those
files in the current directory which have unsual entries.
-f : This option simply terminate the last directory list and signals the
start of file names. This must be used when any of the -B, -M, or -S
options are used. -V: Displays version information and exit. -h: Displays
the help and exit.
317
The printf command
Syntax:
Options:
OPTION Description
FORMAT controls the output, and defines the way that the
FORMAT
ARGUMENTs will be expressed in the output
An ARGUMENT will be inserted into the formatted output
ARGUMENT
according to the definition of FORMAT
--help Display help and exit
--version Output version information adn exit
Formats:
The anatomy of the FORMAT string can be extracted into three different
parts,
318
ARGUMENTs will be expressed as part of the output.
The output:
There are two conversion specifications %s and %d, and there are two
escaped characters which are the opening and closing double-quotes
wrapping the words of the future of software. Other than that are the
ordinary characters.
Conversion Specifications:
319
These differentiate between a short and a long integer,
h or l respectively, and are generally only needed for computer
programming
Conversion
Argument type
char
s A string
An integer, expressed as a character corresponds
c
ASCII code
d, i An integer as a decimal number
o An integer as an unsigned octal number
x, X An integer as an unsigned hexadecimal number
u An integer as an unsigned decimal number
f A floating-point number with a default precision of 6
e, E A floating-point number in scientific notation
p A memory address pointer
% No conversion
Here is the list of some examples of the printf output the ARGUMENT.
we can put any word but in this one we put a 'linuxcommand` word and
enclosed it with quotes so we can see easier the position related to the
whitespaces.
320
Notes:
The input
The output:
The example above shows 3 arguments, 12.07, larger than, and 12.
Each of them interpreted from left to right one-to-one with the given 3
conversion strings (%f, %d, %s).
321
Escaped char Description
\t prints a horizontal tab
\v prints a vertical tab
\" prints a double-quote (")
\\ prints a backslash ()
\NNN prints a byte with octal value NNN (1 to 3 digits)
\xHH prints a byte with hexadecimal value HH (1 to 2 digits)
prints the unicode character with hexadecimal value
\uHHHH
HHHH (4 digits)
prints the unicode character with hexadecimal value
\UHHHHHHHH
HHHHHHHH (8 digits)
prints ARGUMENT as a string with "\" escapes
%b interpreted as listed above, with the exception that
octal escapes take the form \0 or \0NN
Examples:
The format specifiers usually used with printf are stated in the
examples below:
%s
322
integers.
%x, %X - Prints arguments in the format of unsigned
hexadecimal(base 16) integers. %x prints lower-case letters and
%X prints upper-case letters.
%e, %E - Prints arguments in the format of floating-point numbers in
exponential notation. %e prints lower-case letters and %E prints
upper-case.
%a, %A - Prints arguments in the format of floating-point numbers in
hexadecimal(base 16) fractional notation. %a prints lower-case
letters and %A prints upper-case.
%g, %G - Prints arguments in the format of floating-point numbers in
normal or exponential notation, whichever is more appropriate for
the given value and precision. %g prints lower-case letters and %G
prints upper-case.
%c - Prints arguments as single characters.
%f - Prints arguments as floating-point numbers.
%s - Prints arguments as strings.
%% - Prints a "%" symbol.
More Examples:
The input:
printf 'Hello\nyoung\nman!'
The output:
hello
young
man!
The input:
323
printf "%f\n" 2.5 5.75
The output
2.500000
5.750000
324
The cut command
The cut command lets you remove sections from each line of files. Print
selected parts of lines from each FILE to standard output. With no FILE,
or when FILE is -, read standard input.
Here, k denotes the starting position of the character and n denotes the
ending position of the character in each line, if k and n are separated by
“-” otherwise they are only the position of character in each line from
the file taken as an input.
325
cut -b 1,2,3 filename //select bytes 1,2
and 3
cut -b 1-4 filename //select bytes 1
through 4
cut -b 1- filename //select bytes
1 through the end of file
cut -b -4 filename //select bytes
from the beginning till the 4th byte
Syntax:
Short
Long Flag Description
Flag
-b --bytes=LIST select only these bytes
-c --characters=LIST select only these characters
use DELIM instead of TAB for field
-d --delimiter=DELIM
delimiter
select only these fields; also print any
-f --fields line that contains no delimiter character,
unless the -s option is specified
do not print lines not containing
-s --only-delimited
delimiters
-z --zero-terminated line delimiter is NUL, not newline
326
The sed command
The most common use of sed command is for a substitution or for find
and replace. By using sed you can edit files even without opening it,
which is a much quicker way to find and replace something in the file. It
supports basic and extended regular expressions that allow you to
match complex patterns. Most Linux distributions come with GNU and
sed is pre-installed by default.
Examples:
327
Sometimes you may want to recursively search directories for files
containing a string and replace the string in all files. This can be done
using commands such as find to recursively find files in the directory
and piping the file names to sed. The following command will
recursively search for files in the current working directory and pass the
file names to sed. It will recursively search for files in the current
working directory and pass the file names to sed.
Syntax:
328
Short Flag Long Flag Description
Add the script to the commands
-e script --expression=script
to be executed.
-f script- Add the contents of script-file to
file
--file=script-file
the commands to be executed.
Specify the desired line-wrap
-l N --line-length=N
length for the l command.
Use extended regular expressions
-r --regexp-extended
in the script.
Consider files as separate rather
-s --separate than as a single continuous long
stream.
Load minimal amounts of data
-u --unbuffered from the input files and flush the
output buffers more often.
Separate lines by NULL
-z --null-data
characters.
329
The vim command
The vim is a text editor for Unix that comes with Linux, BSD, and
macOS. It is known to be fast and powerful, partly because it is a small
program that can run in a terminal (although it has a graphical
interface). Vim text editor is developed by Bram Moolenaar. It supports
most file types and the vim editor is also known as a programmer's
editor. It is mainly because it can be managed entirely without menus
or a mouse with a keyboard.
Note: Do not confuse vim with vi. vi, which stands for "Visual", is a
text editor that was developed by Bill Joy in 1976. vim stands for "Vi
Improved", and is an improved clone of the vi editor.
The most searched question about vim editor looks very funny but it's
true that the new user gets stuck at the very beginning when using vim
editor.
The command to save the file and exit vim editor: :wq
The command to exit vim editor without saving the file: :q!
Fun reading:
Here's a survey for the same question, look at this and do not think to
quit the vim editor.
330
Installation:
vim --version
If it is already installed it will show its version, else we can run the
below commands for the installations:
On Ubuntu/Debian:
On CentOS/Fedora:
Syntax:
vim [FILE_PATH/FILE_NAME]
331
Examples:
vim demo.txt
vim {File_Path/filename}
There are some arguments as to how many modes that vim has, but
the modes you're most likely to use are command mode and insert
mode. These modes will allow you to do just about anything you need,
including creating your document, saving your document, and doing
advanced editing, including taking advantage of search and replace
functions.
332
5. Type :w or :wq to save the file or save and exit from the file
respectively.
Interactive training
In this interactive tutorial, you will learn the different ways to use the
vim command:
Flags/Options Description
-e Start in Ex mode (see Ex-mode)
-R Start in read-only mode
-R Start in read-only mode
-g Start the GUI
-eg Start the GUI in Ex mode
-Z Like "vim", but in restricted mode
-d Start in diff mode diff-mode
-h Give usage (help) message and exit
Open a file and place the cursor on the line number
+NUMBER
specified by NUMBER
vim can not be learned in a single day, use in day-to-day tasks to get
hands-on in vim editor.
333
The chown command
Examples:
334
Syntax:
335
The find command
Examples:
find . -size 0k
336
Syntax:
In Simple words
name pattern - tests whether the file name matches the shell-glob
pattern given.
type type - tests whether the file is a given type. Unix file types
accepted include:
options Description
b block device (buffered)
d directory
f regular file
l Symbolic link
always returns true; prints the name of the current file
-print
plus a newline to the stdout.
-mtime n find's all the files which are modified n days back.
-atime n find's all the files which are accessed 50 days back.
-cmin n find's all the files which are modified in the last 1 hour.
-newer file find's file was modified more recently than file.
-size n File uses n units of space, rounding up.
337
Help Command
man find
338
The rmdir command
Syntax:
339
Short
Long Flag Description
Flag
ignore each failure that is
- --ignore-fail-on-non-empty solely because a directory is
non-empty
remove DIRECTORY and its
-p --parents
ancestors
use DELIM instead of TAB for
-d --delimiter=DELIM
field delimiter
output a diagnostic for every
-v --verbose
directory processed
340
The lsblk command
341
Summary
The lsblk command displays the block and loop devices on the system.
It is especially useful when you want to format disks, write filesystems,
check the filesystem and know the mount point of a device.
342
Examples
1. Basic usage is fairly simple - just execute 'lsblk' sans any option.
lsblk
lsblk -a
lsblk -b
lsblk -z
lsblk -d
lsblk -i
7. Make lsblk display info about device owner, group, and mode
343
lsblk -m
lsblk -o NAME,SIZE
344
Syntax
345
Reading information given by lsblk
346
Reading information of a specific device
lsblk /dev/sda
347
Useful flags for lsblk
Here is a table that show some of the useful flags that can be used with
lsblk
Short
Long Flag Description
Flag
lsblk does not list empty devices by default. This option disables this
-a --all
restriction.
-b --bytes Print the SIZE column in bytes rather than in human-readable format.
-d --nodeps Don't print device holders or slaves.
Print information about the discard (TRIM, UNMAP) capabilities for each
-D --discard
device.
Use column as a de-duplication key to de-duplicate output tree. If the key
-E --dedup column is not available for the device, or the device is a partition and parental
whole-disk device provides the same key than the device is always printed.
xclude the devices specified by a comma-separated list of major device
-e --exclude list numbers. Note that RAM disks (major=1) are excluded by default. The filter
is applied to the top-level devices only.
-f --fs Displays information about filesystem.
-h --help Print a help text and exit.
-l --include list Displays all the information in List Format.
-J --json Displays all the information in JSON Format.
-l --list Displays all the information in List Format.
-m --perms Displays info about device owner, group and mode.
Group parents of sub-trees to provide more readable output for RAIDs and
-M --merge
Multi-path devices. The tree-like output is required.
-n --noheadings Do not print a header line.
Specify which output columns to print. Use --help to get a list of all
-o --output list
supported columns.
-O --output-all Displays all available columns.
-p --paths Displays absolute device paths.
Use key="value" output format. All potentially unsafe characters are hex-
-P --pairs
escaped (\x)
Use the raw output format. All potentially unsafe characters are hex-
-r --raw escaped (\x) in NAME, KNAME, LABEL, PARTLABEL and MOUNTPOINT
columns.
Output info about SCSI devices only. All partitions, slaves and holder
-S --scsi
devices are ignored.
-s --inverse Print dependencies in inverse order.
Output info about block device topology. This option is equivalent to "-o
-t --topology
NAME,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,ROTA,SCHED,RQ-SIZE".
-T --tree[=column] Displays all the information in Tree Format.
-V --version Output version information and exit.
pecifies output width as a number of characters. The default is the number
-w --width of the terminal columns, and if not executed ona terminal, then output
width is not restricted at all by default.
348
Short
Long Flag Description
Flag
Sort output lines by column. This option enables --list output format by
-x --sort [column] default. It is possible to use the option --tree to force tree-like output and
than the tree branches are sorted by the column.
-z --zoned Print the zone model for each device.
Gather data for a Linux instance other than the instance from which the
--sysroot
-
directory
lsblk command is issued. The specified directory is the system root of the
Linux instance to be inspected.
349
Exit Codes
Like every Unix / Linux Program, lslbk returns an exit code to the
environment. Here is a table of all the exit codes.
350
The cmatrix command
cmatrix
As you can see you have access to the matrix now. Well, not really.
What this actually is just a fun little command to goof around with.
There are actually a few options you can use. For examle you can
change the text colour. You can choose from green, red, blue, white,
yellow, cyan, magenta and black.
cmatrix -C red
And the falling characters will be red. This command isn't really
something that will help you with your job or anything, but it is fun to
know that you can have some fun in Linux.
351
The chmod command
Examples:
352
chmod -R 754 folder
Syntax:
u: user
g: group
o: other
=: set the permission
r: read
w: write
x: execute
example u=rwx means user can read write and execute
353
0 stands for "no permission."
example 7 mean read + write + execute
354
The grep command
The grep filter searches a file for a particular pattern of characters, and
displays all lines that contain that pattern. grep stands for globally
search for regular expression and print out. The pattern that is
searched in the file is referred to as the regular expression.
Examples:
3. We can search multiple files and only display the files that contains
the given string/pattern.
355
5. If you want to grep the monitored log files, you can add the --
line-buffered to search them in real time.
Syntax:
Short
Long Flag Description
Flag
print a count of matching lines for
-c --count
each input file
Display the matched lines, but do not
-h --no-filename
display the filenames
-i --ignore-case Ignores, case for matching
-l --files-with-matches Displays list of a filenames only.
Display the matched lines and their
-n --line-number
line numbers.
This prints out all the lines that do not
-v --invert-match
matches the pattern
Specifies expression with this option.
-e --regexp=
Can use multiple times
-f --file= Takes patterns from file, one per line.
Interpret patterns as fixed strings, not
-F --fixed-strings=
regular expressions.
Treats pattern as an extended regular
-E --extended-regexp
expression (ERE)
-w --word-regexp Match whole word
356
Short
Long Flag Description
Flag
Print only the matched parts of a
-o --only-matching matching line, with each such part on
a separate output line.
--line-buffered Force output to be line buffered.
357
The screen command
screen - With screen you can start a screen session and then open any
number of windows (virtual terminals) inside that session. Processes
running in Screen will continue to run when their window is not visible
even if you get disconnected. This is very handy for running long during
session such as bash scripts that run very long.
To start a screen session you type screen, this will open a new screen
session with a virtual terminal open.
Below are some most common commands for managing Linux Screen
Windows:
Command Description
Ctrl+a+ c Create a new window (with shell).
Ctrl+a+ " List all windows.
Ctrl+a+ 0 Switch to window 0 (by number).
Ctrl+a+ A Rename the current window.
Ctrl+a+ S Split current region horizontally into two regions.
Ctrl+a+ ' Split current region vertically into two regions.
Ctrl+a+ tab Switch the input focus to the next region.
Ctrl+a+ Ctrl+a Toggle between the current and previous windows
Ctrl+a+ Q Close all regions but the current one.
Ctrl+a+ X Close the current region.
358
Restore a Linux Screen
To restore to a screen session you type screen -r, if you have more
than one open screen session you have to add the session id to the
command to connect to the right session.
359
Listing all open screen sessions
To find the session ID you can list the current running screen sessions
with:
screen -ls
18787.pts-0.your-server (Detached)
15454.pts-0.your-server (Detached)
2 Sockets in /run/screens/S-yourserver.
screen -r 18787
360
The nc command
Syntax:
Examples:
$ nc -p 1337 -w 5 host.ip 80
$ nc -u host.ip 80
361
$ nc -lU /var/tmp/dsocket
After the file has been transferred, sequentially, the connection closes
automatically
6. Talk to servers:
7. Port scanning:
362
$ nc -zv host.ip 20-2000 # range of ports to check for
Short
Description
Flag
-4 Forces nc to use IPv4 addresses
-6 Forces nc to use IPv6 addresses
-b Allow broadcast
-D Enable debugging on the socket
-i Specify time interval delay between lines sent and received
-k Stay listening for another connection after current is over
Listen for incoming connection instead of initiate one to
-l
remote
-T Specify length of TCP
-p Specify source port to be used
-r Specify source and/or destination ports randomly
-s Specify IP of interface which is used to send the packets
-U Use UNIX-domain sockets
-u Use UDP instead of TCP as protocol
Declare a timeout threshold for idle or unestablished
-w
connections
-x Should use specified protocol when talking to proxy server
Specify to scan for listening daemons, without sending any
-z
data
363
The make command
How the make command can help us is it can automate all of that in just
one go: make tf-init
Syntax:
364
hello-world:
echo "Hello, World!"
hello-bobby:
echo "Hello, Bobby!"
touch-letter:
echo "This is a text that is being inputted into our
letter!" > letter.txt
clean-letter:
rm letter.txt
365
The basename command
Examples
The most basic example is to print the file name with the leading
directories removed:
basename /etc/bar/foo.txt
foo.txt
If you run basename on a path string that points to a directory, you will
get the last segment of the path. In this example, /etc/bar is a directory.
basename /etc/bar
Output
bar
366
basename /etc/bar/foo.txt/
Output
foo.txt
Options
$ basename -z /etc/bar/foo.txt
foo.txt$
foo.txt
eggs.docx
Syntax
367
basename NAME [SUFFIX]
basename OPTION... NAME...
Additional functionalities
Removing a Trailing Suffix: To remove any trailing suffix from the file
name, pass the suffix as a second argument:
Help Command
man basename
368
The banner command
Note: If you will define more than one NUMBER with sleep command
then this command will delay for the sum of the values.
Examples :
banner LINUX!
banner 101LinuxCommands
369
It will print only 101LinuxCo as banner has a default capacity of 10
370
The alias command
The alias command lets you create shortcuts for commands or define
your own commands.
This is mostly used to avoid typing long commands.
Examples:
1. To show the list of all defined aliases in the reusable form alias
NAME=VALUE :
alias -p
2. To make ls -A shortcut:
Syntax:
As with most Linux custom settings for the terminal, any alias you
defined is only applied to the current opening terminal session.
For any alias to be active for all new sessions you need to add that
371
command to your rc file to be executed in the startup of every new
terminal. this file can be as follows:
Bash: ~/.bashrc
ZSH: ~/.zshrc
Fish – ~/.config/fish/config.fish
you can open that file with your favorite editor as follows:
vim ~/.bashrc
type your commands one per line, then save the file and exit. the
commands will be automatically applied in the next session.
source ~/.bashrc
Opposite command:
unalias alias_name
unalias -a
372
The which command
Examples
which ls
The which command searches from left to right, and if more than one
matches are found in the directories listed in the PATH path variable,
which will print only the first one.
373
which [filename] -a
which node
which java
Syntax
You can pass multiple programs and commands to which, and it will
check them in order.
For example:
Options
-a : List all instances of executables found (instead of just the first one
of each).
374
The date command
The date command is used to print the system current date and time.
date command is also used to set the date and time of the system, but
you need to be the super-user (root) to do it.
Examples:
date
2. You can use -u option to show the date and time in UTC
(Coordinated Universal Time) time zone
date -u
date --date="2/02/2010"
date --date="2 years ago"
Syntax:
375
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
Short
Long Flag Description
Flag
convert the provided string into
-d --date=STRING
formatted date
-f --file=DATEFILE like --date but for files
Display date and time in ISO 8601
-I[FMT] --iso-8601[=FMT]
format
Display the last modification time of
-r --reference=FILE
FILE
sets the time to the one described by
-s --set=STRING
STRING
show the date and time in UTC
-u --universal
(Coordinated Universal Time) time zone
Display date and time in ISO 8601
-R --rfc-email format Example: (Fri, 22 Oct 2021
05:18:42 +0200)
Display date and time in RFC 3339
- rfc-3339=FMT
format
Usually used with --date to annotate
- --debug the parsed date and warn about
questionable usage to stderr
You can use Format specifiers to control the output date and time.
Examples:
376
Command Output
$ date "+%D" 10/22/21
$ date "+%D %T" 10/22/21 05:33:51
$ date "+%A %B %d %T %y" Friday October 22 05:34:47 21
Syntax:
Specifiers Description
%a abbreviated weekday name (e.g., Sun)
%A full weekday name (e.g., Sunday)
%b abbreviated month name (e.g., Jan)
%B full month name (e.g., January)
%c date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 20)
%d day of month (e.g., 01)
%D date; same as %m/%d/%y
%e day of month, space padded; same as %_d
%F full date; same as %Y-%m-%d
%g last two digits of year of ISO week number (see %G)
year of ISO week number (see %V); normally useful only
%G
with %V
%h same as %b
%H hour (00..23)
%I hour (01..12)
%j day of year (001..366)
%k hour, space padded ( 0..23); same as %_H
%l hour, space padded ( 1..12); same as %_I
%m month (01..12)
%M minute (00..59)
377
Specifiers Description
%n a newline
%N nanoseconds (000000000..999999999)
%p locale's equivalent of either AM or PM; blank if not known
%P like %p, but lower case
%q quarter of year (1..4)
%r locale's 12-hour clock time (e.g., 11:11:04 PM)
%R 24-hour hour and minute; same as %H:%M
%s seconds since 1970-01-01 00:00:00 UTC
%S second (00..60)
%t a tab
%T time; same as %H:%M:%S
%u day of week (1..7); 1 is Monday
week number of year, with Sunday as first day of week
%U
(00..53)
ISO week number, with Monday as first day of week
%V
(01..53)
%w day of week (0..6); 0 is Sunday
week number of year, with Monday as first day of week
%W
(00..53)
%x locale's date representation (e.g., 12/31/99)
%X locale's time representation (e.g., 23:13:48)
%y last two digits of year (00..99)
%Y year
%z +hhmm numeric time zone (e.g., -0400)
%:z +hh:mm numeric time zone (e.g., -04:00)
%::z +hh:mm:ss numeric time zone (e.g., -04:00:00)
numeric time zone with : to necessary precision (e.g., -04,
%:::z
+05:30)
%Z alphabetic time zone abbreviation (e.g., EDT)
378
The mount command
Examples:
mount -V
Syntax Forms:
mount [-lhV]
379
Additional Flags and their Functionalities:
Short
Long Flag Description
Flag
-h --help Dispaly a help message and exists
-n --no-mtab Mount without writing in /etc/mtab
Mount all filesystems (of the given types)
-a --all
mentioned in fstab
-r --read-only Mount the filesystem read-only
-w --rw Mount the filesystem as read/write.
-M --move Move a subtree to some other place.
Remount a subtree somewhere else (so that its
-B --bind
contents are available in both places).
380
The nice/renice command
Examples:
Syntax:
Flags :
Long
Short Flag Description
Flag
Increment is the value of priority you want to
-Increment -
assign.
381
Long
Short Flag Description
Flag
-n Increment - Same as -Increment
382
The wc command
the wc command stands for word count. It's used to count the number
of lines, words, and bytes (characters) in a file or standard input then
prints the result to the standard output.
Examples:
wc file.txt
ls -F | grep / | wc -l
Syntax:
wc [OPTION]... [FILE]...
Short
Long Flag Description
Flag
-c --bytes print the byte counts
-m --chars print the character counts
383
Short
Long Flag Description
Flag
-l --lines print the newline counts
read input from the files specified by
- --files0-from=F NUL-terminated names in file F. If F is -
then read names from standard input
-L --max-line-length print the maximum display width
-w --words print the word counts
Additional Notes:
Passing more than one file to wc command prints the counts for
each file and the total conuts of them.
you can combine more whan one flag to print the result as you
want.
384
The tr command
Examples:
$ cat file1
foo
bar
baz
tr a-z A-Z < file1
FOO
BAR
BAZ
385
$ cat file1
foo
bar
baz
$ tr -s "\n" < file1
foo
bar
baz
$ cat file1
foo
bar
baz
$ tr -d "\n" < file1
foobarbaz%
Syntax:
Short Long
Description
Flag Flag
Complement the set of characters in string1, that is
-C
-C ab includes every character except for a and b.
-c Same as -C.
386
Short Long
Description
Flag Flag
-d Delete characters in string1 from the input.
If there is a sequence of characters in string1,
-s
combine them into one.
387
The fdisk command
The fdisk command is used for controlling the disk partition table and
making changes to it and this is a list of some of options provided by it :
Examples:
fdisk -l
fdisk -s /dev/sda
fdisk -h
Syntax:
388
fdisk [options] device
fdisk /dev/sdb
and then you type m which will show you all options you need such as
creating new partition and deleting a partition as in the following
picture :
389
The Wait commands
390
Example
Step-1:
#!/bin/bash
echo "Wait command" &
process_id=$!
wait $process_id
echo "Exited with status $?"
Step-2:
$ bash wait_example.sh
391
The zcat command
Examples:
~$ zcat test.txt.gz
Hello World
Syntax:
392
The fold command
To fold input using the fold command pass a file or standard input to
the command.
Syntax:
Options
By using this command we change the column width from default width
of 80. Syntax:
393
fold -w60 file1.txt
-b : This option of fold command is used to limit the width of the output
by the number of bytes rather than the number of columns.
By using this we can enforce the width of the output to the number of
bytes.
Example: limit the output width of the file to 40 bytes and the command
breaks the output at 40 bytes.
-s : This option is used to break the lines on spaces so that words are
not broken.
If a segment of the line contains a blank character within the first width
column positions, break the line after the last such blank character
meeting the width constraints.
394
The quota command
Installation:
Syntax:
395
The aplay command
396
Syntax:
397
Options:
aplay --help
398
Examples :
$ aplay --version
399
The spd-say command
400
Syntax:
401
Options:
-r, --rate
Set the rate of the speech (between -100 and +100,
default: 0)
-p, --pitch
Set the pitch of the speech (between -100 and +100,
default: 0)
-i, --volume
Set the volume (intensity) of the speech (between -100
and +100, default: 0)
-o, --output-module
Set the output module
-l, --language
Set the language (iso code)
-t, --voice-type
Set the preferred voice type (male1, male2, male3,
female1, female2, female3,
child_male, child_female)
-m, --punctuation-mode
Set the punctuation mode (none, some, all)
-s, --spelling
Spell the message
-x, --ssml
Set SSML mode on (default: off)
-e, --pipe-mode
Pipe from stdin to stdout plus Speech Dispatcher
-P, --priority
Set priority of the message (important, message,
text, notification, progress;
default: text)
-N, --application-name
402
Set the application name used to establish the
connection to specified string value
(default: spd-say)
-n, --connection-name
Set the connection name used to establish the
connection to specified string value
(default: main)
-w, --wait
Wait till the message is spoken or discarded
-S, --stop
Stop speaking the message being spoken in Speech
Dispatcher
-C, --cancel
Cancel all messages in Speech Dispatcher
-v, --version
Print version and copyright info
-h, --help
Print this info
403
Examples :
$ spd-say "Hello"
404
The xeyes command
Syntax:
xeyes
xeyes is not for fun, at least not only. The purpose of this program is to
let you follow the mouse pointer which is sometimes hard to see. It is
very useful on multi-headed computers, where monitors are separated
by some distance, and if someone (say teacher at school) wants to
present something on the screen, the others on their monitors can
easily follow the mouse with xeyes.
405
The parted command
Examples:
sudo parted -l
label-type can take values "aix", "amiga", "bsd", "dvh", "gpt", "loop",
"mac", "msdos", "pc98", or "sun"
406
4. Create a new partition in a specific disk of type part-time, file
system is fs-type and of size size Mb.
407
$ sudo parted
GNU Parted 3.3
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of
commands.
(parted) print # prints the partition table of the default
selected disk - /dev/sda
Model: ATA VBOX HARDDISK (scsi)
Disk /dev/sda: 53.7GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:
Syntax Forms:
Options:
Short
Long Flag Description
Flag
displays a help message listing all possible
-h --help
commands [options]
-l --list lists partition layout on all block devices
-m --machine displays machine parseable output
-v --version displays the version
408
Short
Long Flag Description
Flag
set alignment type for newly created partition. It
can take the following values:
none: Use the minimum alignment allowed by
the disk type
-a --align cylinder: Align partitions to cylinders
minimal: Use minimum alignment as given by
the disk topology information
optimal: Use optimum alignment as given by
the disk topology information
409
The nl command
410
Syntax
411
Examples:
nl -ba chap1
You can name only one file on the command line. You can list the flags
and the file name in any order.
412
The pidof command
The pidof is a command-line utility that allows you to find the process
ID of a running program.
413
Syntax
414
Examples:
pidof sshd
If there are running processes with names matching sshd, their PIDs will
be displayed on the screen. If no matches are found, the output will be
empty.
# Output
4382 4368 811
pidof returns 0 when at least one running program matches with the
requested name. Otherwise, the exit code is 1. This can be useful when
writing shell scripts.
To be sure that only the PIDs of the program you are searching for are
displayed, use the full pathname to the program as an argument. For
example, if you have two running programs with the same name
located in two different directories pidof will show PIDs of both running
programs.
pidof -s program_name
The -o option allows you to exclude a process with a given PID from the
command output:
415
pidof -o pid program_name
When pidof is invoked with the -o option, you can use a special PID
named %PPID that represents the calling shell or shell script.
To return only the PIDs of the processes that are running with the same
root directory, use the -c option. This option works only pidof is run as
root or sudo user:
416
Conclusion
The pidof command is used to find out the PIDs of a specific running
program.
417
The shuf command
418
Syntax
# file shuf
shuf [OPTION] [FILE]
# list shuf
shuf -e [OPTION]... [ARG]
# range shuf
shuf -i LO-HI [OPTION]
Like other Linux commands, shuf command comes with -–help option:
419
Examples:
shuf
4
5
1
2
3
{
seq 5 | shuf
}
420
from 1 to 5. Hence, 1 to 5 is displayed as output in random order.
[user@home ~]$ {
> seq 5 | shuf
> }
5
4
2
3
1
File shuf
shuf file.txt
Suppose file.txt contains 6 lines, then the shuf command displays the
input lines in random order as output.
421
[user@home ~]$ cat file.txt
line-1
line-2
line-3
line-4
line-5
shuf -n 2 file.txt
This will display any two random lines from the file.
line-5
line-2
List shuf
When -e option is used with shuf command, it works as a list shuf. The
arguments of the command are taken as the input line for the shuf.
Consider an example:
shuf -e A B C D E
422
A
C
B
D
E
Any number of input lines can be displayed using the -n option along
with -e option.
shuf -e -n 2 A B C D E
E
A
Range shuf
423
Conclusion
The shuf command helps you randomize input lines. And there are
features to limit the number of output lines, repeat lines and even
generate random positive integers. Once you're done practicing
whatever we've discussed here, head to the tool's man page to know
more about it.
424
The less command
425
Syntax
426
Options
For a complete list of options, refer to the less help file by running:
less --help
427
Few Examples:
less /etc/updatedb.conf
less -N /etc/init/mysql.conf
less welcome.txt
Here I showed you how to use the less command in Linux. Although
there are other terminal pagers, such as most and more, but less could
be a better choice as it is a powerful tool present in almost every
system.
428
The nslookup command
429
Syntax
430
Options
431
Few Examples:
nslookup www.google.com
432
The cmp command
The cmp command is used to compare the two files byte by byte.
Example:
Syntax:
433
Few Examples :
Perform a simple comparison of the two files to check out if they differ
from each other or not.
Example:
Example:
Example:
434
cmp -b list.txt list1.txt
Example:
Example:
Short
Long Flag Description
Flag
-b --print-bytes print differing bytes
skip first SKIP bytes of both
-i --ignore-initial=SKIP
inputs
skip first SKIP1 bytes of
-i --ignore-initial=SKIP1:SKIP2 FILE1 and first SKIP2 bytes
of FILE2
output byte numbers and
-l --verbose
differing byte values
-n --bytes=LIMIT compare at most LIMIT bytes
435
Short
Long Flag Description
Flag
-s --quiet, --silent suppress all normal output
output version information
v --version
and exit
--help Display this help and exit
436
The expr command
437
Syntax
expr expression
438
Few Examples:
expr 7 + 14
expr 7 * 8
x=10
y=20
res=`expr $x = $y`
echo $res
expr 20 % 30
439
5. Extract the substring
a=HelloWorld
b=`expr substr $a 6 10`
echo $b
Flag Description
--version output version information and exit
--help Display this help and exit
999-wrap-up.md
440