Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views29 pages

Linux Commands

Uploaded by

anshuljain14894
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views29 pages

Linux Commands

Uploaded by

anshuljain14894
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Linux Commands

Contents
1 Change SU password (passwd) 3

2 List files and folders (ls) 3

3 EZA (ls with highlighting and git integration) 3

4 Word count (wc) 3

5 Change current directory (chdir/cd) 4

6 Make directory (mkdir) 4

7 Copy files and folders (cp) 4

8 Securely copy files through LAN (SCP) 5

9 Move/Rename files and folders (mv) 5

10 Remove files and folders (rm) 5

11 Remove empty directories (rmdir) 6

12 Global Regular Expression Print (grep) 6

13 Interface Configurnation (ifconfig) 7

14 Trace path of packet flow from source to destination (traceroute) 7

15 ICMP ping (ping) 8

16 Trace packet information (tcpdump) 8

17 Copy disks and partitions from CLI (dd) 11

18 Check filesystem information (df ) 13

19 Check file or folder information (du) 13

20 Show Network Statistics (netstat) 13

21 Process Status (ps) 14

22 Paged text viewer (more) 14

1
23 Concatenate (cat) 15

24 Display or set environment variables (set) 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

26 Linux User, Group and Permission Policy 17

27 Change User (chuser) 18

28 Change Group (chgrp) 18

29 Change Permissions (chmod) 19


29.1 Numeric Mode (Octal Representation) . . . . . . . . . . . . . . . . . . . . . . . 19
29.2 Symbolic Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

30 Binary to ASCII encoding and back (uuencode/uudecode) 20

31 List all previous commands (history) 20

32 Secure Shell (SSH) 21

33 Run SSH commands on a password-protected system (sshpass) 22

34 Detach ssh terminals (screen) (***incomplete***) 22

35 Mount and Unmount filesystems (mount & umount) 23


35.1 mount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
35.2 umount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

36 View system utilization (preinstalled?) 24

37 Find 24

38 FZF (Fuzzy Finder) 27

39 Atuin (command history database) 27

40 BAT (CAT with syntax highlighting) 27

41 TLDR (better, more concise MAN) 27

42 Head and Tail 28


42.1 head . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
42.2 tail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

43 Set DNS/Nameserver 29

44 Fix/reload shell’s cache 29

45 List recently updated packages 29

2
1 Change SU password (passwd)
Execute this command, enter your user password upon prompt followed by the
desired password:
sudo passwd

2 List files and folders (ls)


The ls command is used to list the files and folders in a directory. some of the options of the
ls command are:

1. -a (all): 5. -t Sort by time:


Displays all files and folders, hidden or
not. 6. -r Reverse-order:

2. -l (long listing): 7. -R Recursive:


Displays detailed information about files, Lists subdirectories recursively.
including permissions, owner, size, and
modification date. 8. -S Sort by size:
Sorts files by size, largest first.
3. -h (human-readable):
Used with -l, makes file sizes easier to 9. -i (Inode numbers):
read (e.g., 1K, 234M). Displays the inode number of each file.

4. -d Directories only: 10. -t (Sort by time):


Lists information about directories Sorts files by modification time, newest
themselves, not their contents. first.

3 EZA (ls with highlighting and git integration)


The eza command works in the similar way as ls command i.e. lists the files and folders, but
it highlights the important bits and makes the details more readable along with supporting git
integration. To install eza, execute the following command:
sudo apt-get install eza

4 Word count (wc)


The wc command is used to enumerate the number of lines, words and bytes in a file followed
by the filename. The syntax is:
wc ["options"] "filename"

# When filename is not required in the output


wc ["options"] < "filename"

The options being:

• -l or –lines: Count lines. • -c or –bytes: Count bytes.

• -w or –words: Count words. • -m or –chars: Count characters.

3
• -L or –max-line-length: Print longest • –files0-from=’F’: Read input file-
line. names from file F (F contains filenames).

5 Change current directory (chdir/cd)


To change the current directory, execute the following:
chdir <"Path to the directory">
# Or
cd <"Path to the directory">

Some macros for special directories for the cd or chdir command:

1. . : Present directory. 4. ∼ : Home directory.

2. .. : Parent directory. 5. - : Previously opened directory.

3. ../.. : Parent of parent directory. 6. / : Root directory.

6 Make directory (mkdir)


Execute the following command to create a new directory:
mkdir ["options"] <"Path of the directory_1 to be created"> <"Path of the directory_2 to be \
created"> ...

Options for mkdir are:

• -p : Create nested directory, i.e. all the required parent directories will also get created.

• -v : Prints what got created.

• -mode=MODE : Create a directory with specific access MODE.

You might encounter the following issues when using mkdir:

• 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.

7 Copy files and folders (cp)


Copy (cp) command is used to copy files and folders. The syntax is as follows:
cp ["options"] <"Source"> <Destination>

The options being:

• -i: interactive: should be overwritten.


asks you to confirm if an existing file
• -v: verbose:

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.

8 Securely copy files through LAN (SCP)


Secure Copy (scp) command can be used to securely copy files and folders between two
devices in LAN.
The syntax of scp for copying files is as follows:
scp "<file_name>" "<remoteuser>"@"<remotehost>":"</remote/directory>"

To copy folders, the modification to the command will be as follows:


scp -r "<folder_name>" "<remoteuser>"@"<remotehost>":"</remote/directory>"

You will be prompted for the remote user’s password. The source can be remote too, with the
destination being local.

9 Move/Rename files and folders (mv)


Move (mv) command is a dual-use instruction that can be used to move and rename files and
folders. If the destination directory is different from the cource source directory, then the file
is moved, and if the . The syntax is as follows:
mv ["options"] <"Source"> <Destination>

The options being:

• -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.

10 Remove files and folders (rm)


Remove (rm) command is used to remove files and folders. The syntax is as follows:
rm ["options"] <"Target">

The options being:

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.

11 Remove empty directories (rmdir)


The rmdir command removes the folder mentioned in the argument only if it is empty. The
syntax for rmdir is:
rmdir <option> dir1 dir2 ...

The options for rmdir are:

• --ignore-fail-on-non-empty: Suppresses the non-empty warning.

12 Global Regular Expression Print (grep)


The grep command is a powerful text-searching utility in Unix/Linux used to find lines in a
file or input that match a specified pattern. The syntax for grep is:
grep ["options"] "pattern" ["file..."]

The options for grep are:

• -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"]

# Just for displaying interface configurations and stats:


ifconfig

The options for ifconfig are:

• 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

14 Trace path of packet flow from source to destination


(traceroute)
The traceroute command is a network diagnostic tool used to trace the path packets take
from your system to a destination (usually a domain or IP address). It helps you identify where
delays or failures occur in the network route. The syntax of traceroute is:
traceroute ["options"] <"destination">

The options for traceroute are:

• -n: Do not resolve IP addresses to host- • -q ¡n¿: Number of probe packets per
names (faster). hop (default is 3).

• -m ¡max ttl¿: Maximum number of


• -w ¡wait¿: Wait time (in seconds) for hops to probe (default is 30).
a response from a hop (default is 5 sec-
onds). • -f ¡first ttl¿: Set the first TTL (useful

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.

• -6: Use IPv6 only.


• -I: Use ICMP ECHO instead of UDP
(like ping). • -V: Show version information.

15 ICMP ping (ping)


The ping tool sends ICMP packets to the chosen destination IP. The size and frequency of
sent packets can also be set. The syntax is as follows:
ping <"option"> <"destination">

The options are:

• -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.

16 Trace packet information (tcpdump)


Contrary to the name tcpdump, this tool can trace packets from all protocols. The synax is
as follows:
tcpdump <"option_0"> <"option_modifier_0"> <"option_1"> <"option_modifier_1"> ...

The options are:

• -i: interface: face name, which can be retrieved by exe-


This determines the interface on which cuting ip addr or tcpdump -D. In case
the packets can be sniffed. The op- all the interfaces are to be considered,
tion modifier should contain the inter- then the -i any can be used.

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.

• tcp: only capture TCP packets: • -B: buffer size:


This captures only TCP packets and Specifies the buffer size in bytes as men-
displays the count at the end, op- tioned in option modifier.
tion modifier and “−” is not required.
• -Z: set previleges:
• -s: snaplength: This sets previleges to the user men-
This sets the snapshot length for the tioned by the option modifier
packets to be captured, ie. the first n-
bytes of the packet will be considered. • -K: :
The option modifier should contain the This makes tcpdump refuse checking of
size of the snapshot in bytes, where 0 TCP checksums, option modifier is not
will signify full size. required.

• -n: not resolve addresses to host- • -y: datalink type:


name: This specifies the data link type to the
link type mentioned in option modifier.

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:

1. Host based filters: • dst port <number>: Matches


packets to a port.
• host <IP/hostname>: Matches
• portrange <low>-<high>:
packets to and from a host.
Matches packets in a range of ports.
• src host <IP>: Matches packets
from a host.
4. Protocol filters:
• dst host <IP>: Matches packets
to a host. • ip4: IPv4 traffic
• ip6: IPv6 traffic
• icmp: Internet Control Message
2. Network-Based filters:
Protocol
• net <network>/<CIDR>: • icmp6: ICMP for IPv6
Matches packets to or from a net- • tcp: Transmission Control Proto-
work. col
• src net <network>/<CIDR>: • udp: User Datagram Protocol
Matches packets from a network. • arp: Address Resolution Protocol
• dst net <network>/<CIDR>: • rarp: Reverse ARP
Matches packets to a network.
• ether: Ethernet traffic
• pppoed/pppoes: PPP-over-
3. Port-Based filters: Ethernet Discovery/Session
• vlan: VLAN-tagged traffic

• port <number>: Matches pack-


ets to or from a port. 5. Packet Size filters:
• src port <number>: Matches • greater <bytes>: packets larger
packets from a port. than bytes

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:

• ether host <MAC>: Source or • broadcast: All broadcast traffic.


destination MAC. • multicast: All multicast traffic.

7. Directional Modifiers: 10. Advanced Expressions (Byte-Level


Offsets): (not limited to)
• src: Matches the source address/-
port/etc. • ip[2:2] > 1500: IP total length
• dst: Matches the destination ad- greater than 1500.
dress/port/etc. • tcp[13] & 0x02 != 0: TCP SYN
• src and dst: Both source and des- flag is set.
tination must match • tcp[13] & 0x01 != 0: TCP FIN
• src or dst: Either source or desti- flag is set.
nation matches • udp[8:2] = 53: Specific field in
UDP payload.

Examples of usage of these Filter Expressions are as follows:


tcpdump tcp port 80 # HTTP traffic
tcpdump udp and port 53 # DNS queries
tcpdump icmp # Ping requests/replies
tcpdump src net 192.168.1.0/24 # From local subnet
tcpdump greater 1000 # Large packets only
tcpdump not port 22 # Exclude SSH
tcpdump vlan and port 80 # VLAN HTTP traffic
tcpdump 'tcp and port 443 and not src net 10.0.0.0/8'

17 Copy disks and partitions from CLI (dd)


The dd command can be employed majorly for cloning hard drives, partitions and disk-
images(img’s), but it can also be used for files. The syntax of which is as follows:
sudo dd if=<"source-path"> of=<"destination-path"> ["option"]

Where the option field can be:

1. status: The most common option, • noxfer:Show progress except for


which shows the progress of copying. transfer rates.
• Progress:Most Common Option,
• none:No status output. Show transfer progress during exe-

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:

• excl: By default dd overwrites the • append: Append to the output file


destination file, this conv option instead of overwriting it.
turns of overwriting and make the • direct: Use direct I/O for output
command fail and throw an error in (bypasses the file system cache).
case the destination file exists.
5. bs=<size>: Set both input and output
• notrunc: Disables truncation for
source block size (in bytes).
copying, used with append.
• noerror: Continue copying even if 6. ibs=<size>: Set only input source
there are read errors. block size (in bytes).
• sync: Add every input block to the 7. obs=<size>: Set only output source
specified bs size (useful when input block size (in bytes).
files have variable block sizes).
8. count=<n>: Copy only n blocks.
• fdatasync: Synchronise data to
disk before completing the copy. 9. skip=<n>: Skip n blocks at the begin-
• fsync: Similar to fdatasync, but ning of the input file if used along with
waits until all file metadata is writ- bs.
ten. 10. seek=<n>: Skip n blocks at the begin-
• swab: Swap every pair of bytes. ning of the output file.

Some examples for commonly used dd commands are:


• Create a backup of a disk/partition:
dd if=/dev/sda of=/path/to/backup.img bs=64K status=progress

• Create a bootable USB drive from an ISO image:


dd if=path/to/linux.iso of=/dev/sdX bs=4M status=progress && sync

• Clone a partition, skipping the first 10 blocks:


dd if=/dev/sda1 of=/dev/sdb1 bs=64K skip=10

• Create a disk image and add padding to each block:


dd if=/dev/sda of=disk.img bs=512 conv=sync

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"]

# Or with respect to a directory:


df ["options"] <"directory_path">

The options for df command are:

• -T : Also prints the type of filesystem.

• -h : Prints the sizes in KBs, MBs and GBs.

• -a : Include dummy and pseudo filesystems (like proc, sysfs).

• -x TYPE : Exclude filesystems of a specified TYPE.

• --total : Show a grand total of all space.

If a directory name is mentioned, the disk info of the filesystem containing the folder is printed.

19 Check file or folder information (du)


Execute the following command to display the block count of the mentioned file/folder:
du [options] <"directory/file path">

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:

• -h : Prints the sizes in KBs, MBs and GBs.

• -s : Summarizes total size of each argument (no per-directory breakdown).

• -a : Prints size of all files as well as directories.

• -d N or --max-depth=N : Set the recursive enumeration depth to N.

• -c : Print a total at the end.

20 Show Network Statistics (netstat)


The netstat command (short for network statistics) is a networking tool used in Linux/Unix
(and also in Windows) to display network connections, routing tables, interface statistics,
masquerade connections, and multicast memberships. The syntax of netstat is:
netstat ["options"]

Commonly used options for netstat 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

• -u : Show only UDP connections. • -r : Show routing table

• -l : Show only listening ports. • -i : Show network interface statistics

• -n : Show IP addresses and port num- • -s : Show per-protocol statistics.

21 Process Status (ps)


The ps command in Linux/Unix is used to display information about running processes on the
system. The syntax of ps command is:
ps ["options"]

By default, ps shows only your processes running in the current terminal session.Commonly

used options for ps are:

• aux : Shows all processes with detailed PID, time, etc.).


info (BSD style).
• -l : Shows long format.
• -e or -A : Shows processes in the current
shell. • -p PID : Shows info about a specific
• -u USER : Shows process for a specific process bearing process ID PID
USER.
• --forest : Shows process hierarchy in a
• -f : Shows full format listing (parent tree format.

Key columns in the output:

• PID : Process ID. • RSS : Resident Set Size (RAM used)


• PPID : Parent process ID. • TTY : Terminal associated to the pro-
• USER : User who is the owner of the cess.
process.
• STAT : Process status (e.g., R=running,
• %CPU : CPU usage. S=sleeping, Z=zombie).
• %MEM : Memory usage.
• COMMAND : The command that
• VSZ : Virtual memory size. launched the process.

22 Paged text viewer (more)


more is used to view any file page by page. The page dimensions never cross the terminal
dimensions and hence scrolling is not required. The syntax for more is:
more ["option"] "filename"

The navigation keys are as follows:

14
• SPACE : Scroll down one page. • /pattern : Search for the pattern for-
ward.
• ENTER : Scroll down one line.

• b : Go back by one page. • n : Repeat search forward.

• q : Quit • h : Show help.

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.

• Combine multiple files.

• Create new files.

• Redirect output to other files or commands.


The syntax of cat command is:
cat ["option"] "file_1" "file_2" ...

The options for cat command are:

• -n : Enumerate all lines. one.

• -b : Enumerate non-empty lines. • -E : Show $ at the end of each line.

• -s : Squeeze multiple blank lines into • -T : Show tabs as ˆI.

Some usecases for the cat command are:

• 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

24 Display or set environment variables (set)


The set command in Linux/Unix is a shell built-in used to view, set, or unset shell environment
variables and options. The uses of set command are:
• Display all shell variables and functions.

• Enable or disable shell options.

• Control script behavior (e.g., error handling)

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.

Think of the environment as a context in which your commands or applications run.

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.

Some examples of the environment variables are:


• PATH List of directories where executa- • SHELL The shell you’re using (e.g.,
bles are searched for /bin/bash)

• LANG Language/locale setting


• HOME Your home directory
• EDITOR Default text editor (like nano
• USER Your username or vim)

The path variables can be either temporarily or permanently modified.

25.1 Temporary environment variables (export)


For temporary modification, the export command can be used. the syntax is as follows:
export MYVARIABLE="content"

# To check whether the variable has been initialised:


echo $MYVARIABLE

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.

25.2 Parmanent environment variables


For the existence of the environment variables to be permanent, the variable needs to be
enrolled to either of the following files:
• ∼/.bashrc
• ∼/.bash profile
• ∼/.profile

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">

# For example, if you need the environment variable "PATH" to be printed.


env $PATH
# Or
printenv <"variable_name">

26 Linux User, Group and Permission Policy


Linux is a multi-user operating system. It keeps track of users and controls what each user can
do using:

• User IDs (UIDs): Each person or service that accesses a Linux system is assigned a
user account. The types of users are:

– Root: The superuser with full system privileges.


– Regular: Created for human users.
– System: Used by system processes and daemons.

The user info is stored in /etc/passwd in the following form:


<"user">:x:1000:100:<"FULL_USER_NAME">:/home/<"user">:/bin/bash

Where the fields represent:

– <“user”>: Username – <“FULL USER NAME”>: Full


– x: Password (stored in shadow) name/comment

– 1000: UID – /home/<“user”>: Home directory


– 100: GID (primary group) – /bin/bash: Login shell

• Group IDs (GIDs): Groups define a set of users that share the same permissions on
files or resources. The types of groups are:

– Primary: Assigned when the user is created (one per user).


– Secondary: Additional groups a user may belong to.

Group information is stored in /etc/group in the following form:


developers:x:1001:bob,jane

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.

27 Change User (chuser)


The chuser command in Linux/Unix is used to change the ownership of a file or directory.
The syntax of which is:
chgrp ["OPTIONS"] <"user"> <"file/directory">

Where the common options are:


• -R Recursive : change group for all subdirectories and contents.
• -v Verbose : show what is being done.
• -c : Like verbose, but only shows changed files.

28 Change Group (chgrp)


The chgrp command in Linux/Unix is used to change the group ownership of a file or directory.
The syntax of which is:
chgrp ["OPTIONS"] <"group"> <"file/directory">

Where the common options are:


• -R Recursive : change user for subdirectories and contents.
• -v Verbose : show what is being done.
• -c : Like verbose, but only shows changed files.

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.

Permissions are represented by three categories for each file or directory:

• User (u): The owner of the file.

• Group (g): Users in the group that owns the file.

• Others (o): All other users.

Each category has three types of permissions:

• Read (r): Allows viewing the contents of the file or directory.

• Write (w): Allows modifying the contents of the file or directory.

• Execute (x): Allows executing the file as a program or accessing a directory.

29.1 Numeric Mode (Octal Representation)


Permissions can be set using a three-digit octal number. Each permission type has a numeric
value:

• Read (r) = 4

• Write (w) = 2

• Execute (x) = 1

To set permissions, you sum up the values for each category. For example:

• 7 (rwx) : Read, write, and execute.

• 6 (rw-) : Read and write.

• 5 (r-x) : Read and execute.

• 4 (r--) : Read only.

• 0 (---) : No permission granted.

Numeric Mode Syntax Example:


chmod 755 file.txt
# 7 (rwx) for the owner.
# 5 (r-x) for the group.
# 5 (r-x) for others.

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.

• = : Sets a permission exactly.

Symbolic Mode Syntax Example:


chmod u+rwx,g+rx,o-r file.txt
# full permissions for the owner.
# add read and execute permissions for the group.
# remove read permission for others

Some Common options of chmod are:

• -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.

• --reference=[file] : Sets permissions to match those of another file.

• --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).

30 Binary to ASCII encoding and back (uuencode/u-


udecode)
uuencode (short for Unix-to-Unix encoding) is a historical tool used to encode binary files
into ASCII text so they could be safely transmitted over text-only channels like email or Usenet.

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"

uuencode "ASCII_File" > "Decoded_Binary_File"

31 List all previous commands (history)


The history command is used to list all the previously executed commands. The syntax is:
history

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

The syntax of ssh is:


ssh ["options"] "user"@<"hostname">

Where

• user:
The username for the remote system.

• hostname:
The hostname or IP address of the remote machine.

The common options are:

• -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>"

# For the source being remote


sshpass -p "<source_password>" scp "<source_user_name>"@"<source_IP>":"<directory_of_file>"/\
to_copy.file "<Destination_directory>"

34 Detach ssh terminals (screen) (***incomplete***)


The screen instruction can be employed to detach ssh terminals from their hosts so that
they keep running in the background on the SSH server, even if the connection with the SSH
host is broken or the SSH host goes offline. This can be particularly useful while executing
long and compound instructions using SSH as in cases mentioned above, as soon as the tun-
nel breaks, the remote user is logged out of the system and the execution of the instruction fails.

To install Screen, execute the following command:


sudo apt-get install screen

The syntax for the screen command is:


screen ["option"] <"session_name">

Some common usage syntax for the screen instruction are as follows:

1. screen -S <name x>: 4. screen -R:


Create a new screen (terminal session) If only one screen terminal is in de-
with the session name “name x”. tached state, it will enable the screen
session. If more screen terminals are
2. screen -ls: in detached state , it will list them to
List all the active screens. The list will make a selection.
contain the following information:
5. screen -R <name x>:
• The state of terminals (Attached, Attaches the current root terminal to the
Detached). screen bearing the name name x.

• The PID of each screen. 6. screen -d -R <name x>:


If the screen is already attached to an-
• the name of each screen terminal. other root terminal, it must first be de-
tached using the -d option before it can
3. screen -d <name x>: be attached to this terminal.
Detaches the screen from the current
root terminal. 7. screen -r <number>:

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.

• Ctrl+a Ctrl+a: • Ctrl+a+d:


detach terminal.
• Ctrl+a+S:
Split terminal horizontally into regions • Ctrl+a+\:
and press Ctrl+a c to create new win- quit screen.
dow there.
• Ctrl+a+?:
• Ctrl+a+r: displays help screen i.e. the list of com-
resize region. mands.

35 Mount and Unmount filesystems (mount & umount)


The mount and umount commands are used to manage filesystems. They allow you to
connect and disconnect storage devices or partitions, making them accessible for reading and
writing.

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).

Some of the common options being:

• -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">

The common options being:

• 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.

36 View system utilization (preinstalled?)


• The mpstat instruction can be executed to view CPU utilization in a remote system
without installing htop:

• 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

• path: the directory where you want to start the search.

• condition: the search condition (e.g. by name, type, size).

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.

The options are:

1. -name: Find files by name. Eg:


# Find files named example.txt
find /path/to/search -name "example.txt"

2. -type: Find files by type (f, d, l). Eg:


# Find directories
find /path/to/search -type d

3. -size: Find files by size. Eg:


# Find files larger than 100MB
find /path/to/search -size +100M

4. -mtime: Find files by modification time (days). Eg:


# Find files modified in the last 7 days
find /path/to/search -mtime -7

5. -atime: Find files by access time (days). Eg:


# Find files accessed in the last 7 days
find /path/to/search -atime -7

6. -ctime: Find files by change time (days). Eg:


# Find files changed in the last 7 days
find /path/to/search -ctime -7

7. -exec: Execute a command on found files. Eg:


# Delete files named example.txt
find /path/to/search -name "example.txt" -exec rm {} \;
# The {} is the placeholder that "find" instruction replaces with the current file name \
it's processing.
# The \; signifies the end of the -exec command.
# The backslash (\) is used to escape the semicolon (;) so that the shell interprets it \
correctly as part of the find command rather than as a command separator.

8. -delete: Delete found files. Eg:

25
# Delete files larger than 100MB
find /path/to/search -size +100M -delete

9. -user: Find files by user. Eg:


# Find files owned by user john
find /path/to/search -user john

10. -group: Find files by group. Eg:


# Find files owned by group admin
find /path/to/search -group admin

11. -perm: Find files by permissions. Eg:


# Find files with 755 permissions
find /path/to/search -perm 755

12. -mindepth: Minimum search depth. Eg:


# Start search at least 2 directories deep
find /path/to/search -mindepth 2

13. -maxdepth: Maximum search depth. Eg:


# Search up to 3 directories deep
find /path/to/search -maxdepth 3

14. -empty: Find empty files or directories. Eg:


find /path/to/search -type d -empty

15. -prune: Exclude directories from search. Eg:


# Exclude dir_to_exclude directory
find /path/to/search -path "dir_to_exclude" -prune -o -print

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).

To check for the exact phrase, the following command is to be used:


fzf -q <"phrase"> -e

The phrases support regex too.

39 Atuin (command history database)


ATUIN is a command history database which replaces the up key or ctrl + R combinations
and will show you an interface containing all the commands you have executed.
• To install atuin, execute the following command, log-out and then log back in.
curl --proto '=https' --tlsv1.2 -LsSf https://setup.atuin.sh | sh

• To uninstall atuin, execute the following command:


sudo rm -f /home/rahu_g/.atuin/bin/atuin && rm -rf ~/.config/atuin ~/.local/share/atuin ~\
/.cache/atuin

Now remove the entry in .bashrc relating to atuin, specially the line:
eval “$(atuin init bash)”

40 BAT (CAT with syntax highlighting)


To install BAT, execute the following command:
sudo apt-get install bat

41 TLDR (better, more concise MAN)


TLDR provides shortened output for the MAN command for widely used functions. To
install tldr, execute the following command:
sudo apt-get install tldr

The syntax for tldr is:


tldr <"command name">

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.

• file: is the name of the file under observation.

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.

• file: is the name of the file under observation.

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

44 Fix/reload shell’s cache


Execute the following command to refrest the shell’s cache.
hash -r

This can be used in cases where a package is uninstalled but the shell still remembers the
command to the package/app.

45 List recently updated packages


Executing the following command will list all the recently updated packages.
cat /var/log/dpkg.log | grep "\ install\ "

29

You might also like