Linux Commands
Linux Commands
Contents
1 Change SU password (passwd) 3
1
23 Concatenate (cat) 15
25 Environments 16
25.1 Temporary environment variables (export) . . . . . . . . . . . . . . . . . . . . . 16
25.2 Parmanent environment variables . . . . . . . . . . . . . . . . . . . . . . . . . . 16
25.3 Printing environment variables (env/printenv) . . . . . . . . . . . . . . . . . . . 17
37 Find 24
43 Set DNS/Nameserver 29
2
1 Change SU password (passwd)
Execute this command, enter your user password upon prompt followed by the
desired password:
sudo passwd
3
• -L or –max-line-length: Print longest • –files0-from=’F’: Read input file-
line. names from file F (F contains filenames).
• -p : Create nested directory, i.e. all the required parent directories will also get created.
• Folder exists : Folder creation attempt was done on a directory already exists (-p
overrides it).
• Permission denied : The access permission denies modification rights, so folder cannot
be created.
4
to show the files being copied one by one. • -r: recursive:
to copy all the subdirectories and files in
• -f : force: a given directory and preserve the tree
overrides all interactivity and executes structure.
the instruction without returning any
prompts.
You will be prompted for the remote user’s password. The source can be remote too, with the
destination being local.
• -i: interactive:
asks you to confirm if an existing file should be overwritten.
• -v: verbose:
to show the files being moved individually.
• -f : force:
overrides all interactivity and executes the instruction without returning any prompts.
5
• -i: interactive: the instruction without returning any
asks you to confirm if an existing file prompts.
should be overwritten.
• -r: recursive:
• -v: verbose:
to remove all the sub-directories and files
to show the files being removed one by
in a given directory.
one.
• -f : force: • -d: directory trim:
overrides all interactivity and executes removes all the empty directories.
• -i: Ignore case (case-insensitive search). • -w: Match whole words only.
• -v: Invert match – shows lines that do • -x: Match entire lines only.
not match the pattern.
• -e: Specify multiple patterns.
• -r / -R: Recursive search through direc-
tories.
• -f ¡FILE¿: Take patterns from a file,
• -l: Show only the names of files with one per line.
matching lines.
• -A ¡NUM¿: Show NUM lines after
• -L: Show only names of files without match.
matching lines.
• -B ¡NUM¿: Show NUM lines before
• -n: Show line numbers with matching
match.
lines.
• -c: Count the number of matching lines. • -C ¡NUM¿: Show NUM lines before
and after match (context).
• -o: Show only the matching part of the
line. • –color=auto: Highlight matching text.
6
13 Interface Configurnation (ifconfig)
The ifconfig command in Linux is used to view and configure network interfaces. Although
it’s now deprecated in favor of the ip command from the iproute2 suite, it’s still widely used
for basic tasks in many systems, especially for legacy or minimal environments. The syntax
for ifconfig is:
ifconfig <"interface"> ["options"]
• interface: Specify the name of the in- • del: Remove an IP address (alias) from
terface (e.g., eth0, wlan0, lo) an interface
• up: Activates the specified interface • pointopoint: Set the point-to-point IP
address (used for PPP links)
• down: Deactivates the specified inter-
face • arp: Enable/disable ARP (Address Res-
olution Protocol)
• inet addr: Set the IPv4 address
• promisc: Enable/disable promiscuous
• netmask: Set the subnet mask
mode (interface captures all packets)
• broadcast: Set the broadcast address
• allmulti: Enable/disable all-multicast
• mtu: Set the Maximum Transmission mode
Unit size
• txqueuelen: Set length of transmit
• hw: Set hardware (MAC) address queue
• add: Add a new IP address (alias) to an • -a: Show all interfaces, including inac-
interface tive ones
• -n: Do not resolve IP addresses to host- • -q ¡n¿: Number of probe packets per
names (faster). hop (default is 3).
7
if you want to start from a specific hop). • -T: Use TCP SYN packets instead of
UDP.
• -p ¡port¿: Use a specific destination
port (default is 33434). • -4: Use IPv4 only.
• -c <count>: • -n :
Stop after sending <count> packets. Numeric output only – no DNS lookups.
• -i <interval>: • -4 :
Keep interval of <interval> seconds be- Force using IPv4.
fore sending the next packet.
• -t <ttl>: • -6 :
Set the time to live to <ttl>. Force using IPv6.
• -s <size>: • -W <timeout>:
Set the size of the icmp packets to Time to wait for a reply for <timeout>
<size> bytes seconds.
• -q :
Quiet output – only shows summary af- • -D :
ter completion. Print timestamp before each line of out-
put.
• -f :
Flood ping – sends packets as fast as pos- • -O :
sible (requires root). Use with caution! Report when packets are not received.
8
• -D: display all interfaces: • -nn: not resolve hostnames or
This will print all available interfaces ports:
where tcpdump can be executed on, op-
tion modifier is not required.
• -v, -vv, -vvv: verbose levels:
• -c: capture: This sets the verbose level, -v gives basic
This determines the number of packets verbose, -vvv gives most verbose. op-
to be captured. The option modifier tion modifier is not required.
should contain the number of packets af-
ter which tcpdump ends execution. • -e: ethernet headers:
This displays the content of the ethernet
• -A: print in ASCII: headers, option modifier is not required.
This makes the packet content to be
printed in ASCII format, option modifier • -q: quick summary:
is not required. This is similar to -v and gives a quick
summary, option modifier is not re-
• -w: write captured packets to a file: quired.
This writes the captured packets from
tcpdump onto the file mentioned in the • -X: hex and ASCII content:
option modifier. Shows the contents of the packet as hex
and ASCII side by side, option modifier
• -r: read captured packets from a is not required.
file:
This reads the captured packets from the • -XX: content + link level headers:
file mentioned in the option modifier. Shows the contents of the packet as hex
and ASCII side by side along with the
• -U: real time write: link level headers, option modifier is not
This is used with the “-w” command to required.
write onto the mentioned file in realtime.
• -A: ASCII:
• -n: capture and enumerate packets Show packet contents in ASCII only, op-
with IP address: tion modifier is not required.
This captures all packets having an IP
address and displays the count at the • -F: file:
end, option modifier is not required.
9
• -j: timestamp format: • -G: period:
This sets the timestamp format to the This makes tcpdump repeat an action
following formats when mentioned in the after n-seconds as mentioned in the op-
option modifier: tion modifier.
– host: Use the host machine’s de- • -C: size to rotate on:
fault timestamp format. This is used along side the writing op-
– ad: Use the adapter’s timestamp if erations where the file is rotated after it
supported. reaches the desired size as mentioned in
the option modifier. File size never ex-
– sys: Use system timestamps, from ceeds the mentioned size.
the system clock.
– mono: Use monotonic timestamps, • -W: number of files to rotate on:
which are not effected by changes in This is used along -U option such that
system time. it maintains a specified number of files
mentioned in the option modifier, of the
• -J: list timestamp types: required size mentioned in the -U option.
This lists all the supported timestamp All the files will have the maximum file
formats, option modifier is not required. size as the defined size.
There are also Filter Expressions for tcpdump which are categorised as follows:
10
• less <bytes>: packets smaller 8. Logical Operators:
than bytes
• and: Logical AND.
• or: Logical OR.
6. Ethernet and MAC filters:
• not: Logical NOT.
• ether src <MAC>: Source MAC • not: Grouping expression.
address.
• ether dst <MAC>: Destination
MAC address. 9. Broadcast and Multicast:
11
cution. 3. : Set input flags for the operation. Ex-
amples:
2. conv: The conv option can be used to
convert the contents of the selected files. • fullblock: Pad incomplete blocks
Some modifiers for conv are: from the input with zero bytes.
• direct: Open the input file for di-
• ucase: Copies and converts the rect I/O.
characters of the file to uppercase.
• lcase: Copies and converts the 4. oflag: Set output flags for the operation.
characters of the file to lowercase. Examples:
The dd command is very versatile and powerful, but it’s also potentially destructive if misused
(e.g., writing to the wrong disk). Always double-check your if and of parameters before
running a command.
12
18 Check filesystem information (df )
Execute the following command to display the block count, used and available storage and
mount location of the filesystem:
df ["options"]
If a directory name is mentioned, the disk info of the filesystem containing the folder is printed.
If the path chosen is that of a folder, then du recursively enumerates the sizes of all the
subdirectories of the directory too.The options for du are:
13
• -a : Show all connections (listening as bers numerically.
well as non-listening).
• -p : Show PID/program name of the
• -t : Show only TCP connections. connection owner
By default, ps shows only your processes running in the current terminal session.Commonly
14
• SPACE : Scroll down one page. • /pattern : Search for the pattern for-
ward.
• ENTER : Scroll down one line.
more command can be used along with pipes to view the output of commands page by page.
23 Concatenate (cat)
The cat command in Linux/Unix is short for “concatenate”. It’s used for:
• Display the content of a file.
• View a file’s contents: cat file.txt • Append text to a file: cat ¿¿ exist-
ing.txt
• View multiple files together: cat
file1.txt file2.txt
• Create a new file from terminal input: • Combine files into one: cat part1.txt
cat ¿ newfile.txt part2.txt ¿ full.txt
15
• Assign positional parameters
The syntax of set command is:
set ["options"] [--] ["arguments"...]
25 Environments
In Linux, an environment is a collection of settings that define how processes behave. These
settings are passed from the shell (or parent process) to the programs you run. The environ-
ment includes environment variables.
Environment variables are key-value pairs that store configuration information. They con-
trol how processes behave, and are used by the shell, system, and applications.
The environment variable created using export will be destroyed as soon as the shell it was
created on is closed.
The env command in Linux is used to run a program in a modified environment or display
the current environment variables. It’s commonly used in scripting and debugging to manage
environment variables temporarily for the command you’re about to run.
16
25.3 Printing environment variables (env/printenv)
The env of printenv can be used to print the environment variables. The syntax of these
commands are:
# To print all the environment variables
env
# Or
printenv
# To print only a specific variable (notice printenv does not require $):
env $<"variable_name">
# Or
printenv <"variable_name">
• User IDs (UIDs): Each person or service that accesses a Linux system is assigned a
user account. The types of users are:
• Group IDs (GIDs): Groups define a set of users that share the same permissions on
files or resources. The types of groups are:
17
Which means that the group developers (GID 1001) has users bob and jane as
members.
• Permissions (read/write/execute): Every file or resource has permissions mentioned
in three fields, where each field consists of 3 bits representing read, write and execute
respectively:
– Owner: Represented by the first field, defines the permissions of the owner of the
file or resource.
– Group: Represented by the second field, defines the permissions of the members of
the group assigned to it or to which the owner of the file or resource belongs.
– Others: Represented by the third field, defines the permissions of every other
member who is not an owner or is in the group to which the file/resource belongs.
For example:
-rw-r--r-e 1 bob developers 5200 Aug 3 report.txt
– Owner: bob
– Group: developers
– Permissions:
∗ Owner rw-: Can read and write.
∗ Group r--: Can only read.
∗ Others r-e: Can read and execute.
18
29 Change Permissions (chmod)
The chmod (change mode) command in Linux is used to change the file permissions of a
file or directory. Permissions dictate who can read, write, or execute a file, helping maintain
security in multi-user environments.
• Read (r) = 4
• Write (w) = 2
• Execute (x) = 1
To set permissions, you sum up the values for each category. For example:
19
29.2 Symbolic Mode
You can also modify permissions symbolically, using letters to represent permissions and cate-
gories:
• + : Adds a permission.
• - : Removes a permission.
• -R : Changes permissions for all files and subdirectories within a specified directory.
• -v : Displays a message for each file processed, showing what has been changed.
• -c : Similar to -v, but only displays a message if changes are actually made.
• --preserve-root : Ensures the root directory (/) is not affected during a recursive oper-
ation.
• -f : Suppresses most error messages if the command encounters issues with certain files
(e.g., files it cannot change).
It is used in conjunction with uudecode which decodes the ASCII files to binary. The syntax
for uuencode and uudecode are:
uuencode "Binary_File" > "Intended_ASCII_File"
20
32 Secure Shell (SSH)
The Secure Shell (ssh) command in Linux is used to securely connect to a remote server or
computer over a network. It encrypts the data being sent over the network, ensuring secure
communication. SSH is commonly used for remote login, file transfer, and running commands
on a remote machine. To enable SSH, the SSH Server needs to be installed and the SSH
service needs to be started. Execute the following command to do that:
sudo apt-get install openssh-server
sudo systemctl start ssh
# Check the status of the SSH Service
sudo systemctl status ssh
Where
• user:
The username for the remote system.
• hostname:
The hostname or IP address of the remote machine.
• -p [port]: Specifies a port to connect to at the specified local port, which can
on the remote host. SSH defaults to port forward traffic to multiple remote ad-
22, but some servers use different ports dresses.
for security.
• -f : Requests SSH to go to the back-
• -i [identity file]: Specifies the path to a ground just before command execution,
private key file to use for authentication useful for creating persistent connections
instead of a password. or tunnels.
• -X or -Y: Enables X11 forwarding, al- • -N: Tells SSH not to execute a remote
lowing graphical applications to be dis- command, often used with port forward-
played on your local machine. -X is more ing.
secure (restricted), while -Y is more per-
missive. • -T: Disables pseudo-terminal allocation,
useful for running remote commands
• -L [“local port”:“remote host”] that do not require a terminal.
(Local Port Forwarding) Forwards
traffic from a local port to a specified re- • -q: Suppresses warning and diagnostic
mote host and port, useful for accessing messages, making output quieter.
remote services locally. • -C: Enables compression for faster trans-
• --R [“remote port”:“local host”] fer of data, especially useful on slow con-
(Remote Port Forwarding): For- nections.
wards traffic from a port on the remote
• -o [option=value]: Sets SSH configu-
machine to a local port on your machine.
ration options, which are useful for ad-
• -D [“local port”] (Dynamic Port vanced settings like ConnectTimeout or
Forwarding): Creates a SOCKS proxy StrictHostKeyChecking.
21
33 Run SSH commands on a password-protected system
(sshpass)
On a password-protected system, the sshpass command can be used to execute commands
that will require a password. This can be very useful if a command needs to be a single line
so that it can be passed from a script, say from Python or Bash. For example, to copy a file
from a password-protected system using scp, the format of the command will be:
# For the destination being remote
sshpass -p "<destination_password>" scp to_copy.file "<destination_user_name>"@"<destination_IP\
>":"<directory_to_copy>"
Some common usage syntax for the screen instruction are as follows:
22
Enable a session with screen terminal 8. screen -t <name x> -S <name y>:
that has PID “number”.
Some common screen commands executable from inside the screen are:
• Ctrl+a+c: • Ctrl+a+f :
Create new window. fit screen to new terminal size.
• Ctrl+a+k: • Ctrl+a+x:
Kill the current window/session. remove/delete region.
• Ctrl+a+<0-9>:
Go to a window numbered 0 9, use • Ctrl+a+tab:
Ctrl+a w to see number. move to the next region.
35.1 mount
The mount command is used to attach a filesystem to a specified directory in the Linux
directory tree. The syntax of the mount command is:
mount ["options"] <"device"> <"mount_point">
Where:
• device: The path to the device or partition you want to mount, such as /dev/sda1 for
a hard drive partition.
• mount point: The directory where you want to access the mounted filesystem (e.g.,
/mnt or /media).
• -t:
specifies the filesystem type (e.g., ext4, ntfs, etc.).
23
• -o ro:
mounts the filesystem in read-only mode.
• -o rw,noexec,nosuid:
rw enables read-write, noexec prevents executable files from running, and nosuid ignores
setuid bits for security.
• -o rw,remount:
remounts the directory in read-write mode.
35.2 umount
The umount command is used to detach a filesystem from the directory tree, safely unmount-
ing it to avoid data corruption. The syntax od the umount command is:
umount ["options"] <"mount_point">
# Or
umount ["options"] <"device">
• f:
forces the unmount. Use carefully, as it can disrupt data integrity.
• l:
lazily detaches the filesystem immediately but completes the unmount once it’s no longer
in use.
• The free instruction can be executed to check the total, used and free physical and swap
memory on a remote system.
• The top instruction can be executed to get total and per-process real-time CPU and
Memory usage. To exit, an manual interrupt must be issued.
37 Find
The find command in Linux is a powerful tool for searching files and directories within a
directory hierarchy. It allows users to locate files based on a variety of criteria, such as name,
size, modification time, and permissions. The syntax of the find command is as follows:
find <"path"> ["condition_1"] <"criteria_1"> -and ["condition_2"] <"criteria_2"> -or ["\
condition_3"] <"criteria_3">...
Where
24
• criteria: the criteria on which the search condition works on (e.g. the name string, or
the size in numerals).
Note: Find does not recursively searches for files and directories, so regex should be appiled.
25
# Delete files larger than 100MB
find /path/to/search -size +100M -delete
16. -and: Connect two conditions where both must be true. Eg:
# To find all .txt files larger than 1MB
find . -type f -name "*.txt" -and -size +1M
17. -or: Connect two conditions where either one can be true. Eg:
# To find files either named example.txt or modified in the last 2 days:
find . -name "example.txt" -or -mtime -2
26
38 FZF (Fuzzy Finder)
FZF is a fuzzy finder which is a more powerful command than find. It can be installed by
executing the following instruction:
sudo apt-get install fzf
To find a file by the phrase contained by it’s path, the instruction to be executed will be as
follows:
fzf -q <"phrase">
It searches all the paths within the current directory recursively and returns all the paths which
contain the phrase, albeit not exactly matching the phrase (there might be character between
the letters, but the order of the phrase will not change).
Now remove the entry in .bashrc relating to atuin, specially the line:
eval “$(atuin init bash)”
On running the first time, it will download the tldr database for the commands.
27
42 Head and Tail
The head and tail instructions are used to print the top and bottom lines of a file respectively.
They can be useful to read logs or check database files.
42.1 head
The head command is used to print the top lines of a file. By default, it prints the top 10
lines of the file under observation.
The Syntax of head:
head ["option"]<"option_modifier"> <"file">
Where
• option: Selects the option, like:
1. -n or --lines: Prints the first ‘num’ lines instead of first 10 lines. The option modifier
field is mandatory.
2. -c or --bytes: Prints the first ‘num’ bytes from the file specified. Newline count as
a single character, so if head prints out a newline, it will count it as a byte. The
option modifier field is mandatory.
3. -q or --quiet: Is used if more than 1 file is given. Because of this command, data
from each file is not precedes by its file name.
4. -v or --verbose: By using this option, data from the specified file is always preceded
by its file name.
• option modifier: defines the quantity modifying the options, like number of lines/bytes
etc.
42.2 tail
The tail command is used to print the bottom lines of a file. By default, it prints the bottom
10 lines of the file under observation
The Syntax of head:
tail ["option"] <"option modifier"> <"file">
Where
• option: Selects the option, like:
1. -n or --lines: Prints the first ‘num’ lines instead of first 10 lines. The option modifier
field is mandatory.
2. -c or --bytes: Prints the first ‘num’ bytes from the file specified. Newline count as
a single character, so if head prints out a newline, it will count it as a byte. The
option modifier field is mandatory.
3. -q or --quiet: Is used if more than 1 file is given. Because of this command, data
from each file is not precedes by its file name.
4. -v or --verbose: By using this option, data from the specified file is always preceded
by its file name.
28
5. -f or --follow: Using this option will make the changes in the file to be continuously
printed onto the screen. It is useful when reading log files. The screen will not return
to prompt and requires executing manual interrupt in order to stop and return the
control to prompt.
• option modifier: defines the quantity modifying the options, like number of lines/bytes
etc.
43 Set DNS/Nameserver
The DNS/Nameserver is set ind the file /etc/resolv.conf. Just include the following line to
add the DNS server to list:
nameserver <"dns IP address">
# For example:
nameserver 8.8.8.8
This can be used in cases where a package is uninstalled but the shell still remembers the
command to the package/app.
29