Linux commands briefly explained
Updated 29 October 2024
ln
The ln command creates symbolic links ( symlink for short or soft links) and hard links in Linux. This utility comes pre-installed on every Linux distro.
Example of creating a soft link:
sudo ln -s /opt/cleanup.sh /bin/cleanup
Useful ln commands and options
- ln example.txt ~/example.txt - creates a hard link to a file example.txt
- ln -sf /opt/cleanup.sh /bin/cleanup - remove the existing destination file if it already exists and create a new link.
rm
The rm command is a Linux built-in used to delete files and directories.
Simply typing the rm command followed by a filename will permanently delete the file from the system thereby freeing up some disk space.
Example
rm hello.txt
Useful options
- rm -f - forcefully delete a write-protected file.
- rm -rf - recursively delete a directory and all of its contents without confirmation.
- rm -i - prompts the user to confirm the deletion of files.
- rm -d - deletes empty directories only. Same as rmdir command.
zip
The zip command is used to compress one or more multiple files into a single file with the .zip file extension.
Example:
zip compressed_output.zip filename1 filename2 filename3
Useful options:
- zip -r - recursively compress a directory in its file into a single zip file.
- zip -e - password protect a zip file.
- zip -d - delete a specific file from a zip file.
- zip -u - add files to a zip file.
- zip -v - verbose
The zip command does not come pre-installed on most Linux distros. Refer to your distro documentation on how to install it.
wc
The wc command in Linux is used to count the number of lines, words, and characters in text files. The name wc stands for word count.
Example:
wc data.txt
Useful options:
- wc -w - prints the number of words in a given line
- wc -c - prints the number of characters/bytes in a file.
- wc -l - prints the number of lines in a given line
shred
The shred command in Linux is used to securely delete files, making it very difficult to recover the original content of the files.
Shred works by overwriting the file's data multiple times with random patterns. The shredded file can then be deleted from the file system using other commands like rm.
Example:
shred file1.txt
Useful Options:
- shred -u - Removes the after after shredding it.
- shred -s - shred specified bytes in a file.
- shred -v - verbose mode
- shred -n - specify the number of times to overwrite data
stat
stat (short for status) is a Linux command-line utility for displaying detailed information about specific files or file systems. It is commonly used to obtain file timestamps.
Example:
stat example.txt
Useful options:
- stat --format - used to format the stat output.
- stat -f - display filesystem status instead of file status.
uptime
The uptime command is a Linux utility used to check how long a system has been running since its last reboot. It provides information about the current time, the system's uptime, the number of users currently logged in, and system load averages for the last 1, 5, and 15 minutes.
Example:
uptime
Useful options:
- p, --pretty - display the uptime in a more human-friendly format.
- h, --help - display help information.
- s, --since - show the date and time since the system was last started.
uname
The uname command (short for Unix name) is a Linux utility used to display information about the operating system and the system hardware.
Example
uname -a
This will display all the available system and hardware information.
Useful Options:
uname -s - display the kernel name.
uname -r - display the kernel release version.
uname -p - display the process type.
uname -o - display the operating system name.
shutdown
The shutdown command in Linux is used to gracefully shut down or reboot the system.
Here is an example
shutdown
This will schedule the system to be shut down in 1 minute.
Useful options:
- shutdown now - immediately shut down the system.
- shutdown -h - explicitly specify the time you want the system to shut down.
- shutdown -r - reboot the system.
- shutdown -c - cancel the scheduled shutdown.
reboot
The reboot command is a Linux utility used to reboot the system. It is the original and direct way to initiate a system reboot.
Example
reboot
Useful options:
- reboot -f - forcefully reboots your Linux operating system.
- reboot -p - Powers off your system immediately.
- reboot -w - Writes only the wtmp shutdown entry but does not reboot your system.
- –verbose - Writes detailed message when rebooting, which is useful to debug reboot problems.
du
The du (short for disk usage) command in Linux is used to estimate and display the disk space used by files and directories in the file system.
Example:
du
Useful options:
- du -h - display disk usage in human-readable format (eg: KB, MB, GB...)
- du -a - display disk usage of all files and directories including hidden files.
- du -s - display a summarized disk usage view, only showing the final total.
df
The df (short for disk free) command in Linux is used to display the amount of free and used disk space on each filesystem. It details the amount of disk space used, available space, and capacity for mounted file systems.
Example
df -h
This displays the disk space usage in human-readable format for all mounted file systems.
Useful options:
- df -x - exclude specified filesystem types.
- df -i - displays inode usage.
- df –total - displays total available disk space across all the mounted systems.
- df -T - shows the filesystem type.
lsblk
The lsblk (short for list block) command in Linux is used to display all available block devices in Linux (mounted or not), which typically includes physical storage devices like hard drives, solid-state drives, and partitions, as well as virtual devices like loop devices and LVM logical volumes.
Example:
lsblk
Useful Options:
- lsblk -a: Lists all block devices, including the ones that are not in use.
- lsblk -f: Shows file system type, label, and UUID in the output.
- lsblk -m: Displays the information with permission masks.
- lsblk -o: Allows you to specify which columns to display in the output.
- lsblk -b: Display size in bytes instead of in a human-readable format.
- lsblk -l: Displays the information in a list format, rather than a tree format.
- lsblk -p: Shows the full path of each device in the output.
blkid
The blkid (short for block identifier) command in Linux is used to display information about block devices. It retrieves filesystems, partitions, and block devices information such as UUIDs, filesystem types, labels, and other metadata. The blkid command is especially helpful for identifying storage devices and their associated filesystems or labels.
Example:
blkid
Useful options:
- blkid -s - display devices based on the specified tag
- blkid -U - search devices based on their UUID.
- blkid -t - search block devices based on tokens.
date
The date command in Linux is used to display or set system date and time. It allows users to display time in various formats and calculates the past and future dates.
Example:
date
This command will display the day of the week,day of the month, the current month, the year, the current time, and timezone set on your operating system.
Useful Options
- date -d - allows you to displays past, upcoming or future dates.
- date + - allows you to specify the output format.
- date -r - displays the last modification date of a specified file.
- date –set - allows you to set the date and time of your system.
hostname
The hostname command is Linux command-line utility used to to view or set the system's hostname and domain name.
Example:
hostname
This command displays the current hostname set on the system.
Useful Options
- s - Displays the short hostname (up to the first .).
- a - Displays the alias name of the host (if used).
- i - Shows the IP address of the host.
- I - Shows all network addresses of the host.
- f - Displays Fully Qualified Domain Name (FQDN).
- d - Shows the DNS domain name.
- y - Displays the NIS/YP domain name.
- F - Read the hostname from the given file.
fdisk
The fdisk command is a Linux menu-based command-line utility used for disk partitioning. It allows users to create, delete, modify, and manage disk partitions on the system.
Example:
fdisk -l
This command displays all available disk partitions on the system.
Useful options:
- fdisk -x - same as fdisk -l but provides a detailed list of partitions on the system.
- fdisk -L - displays colored output.
- fdisk -o - specifies which columns to output.
mount
The mount command in Linux is an essential tool used to attach filesystem or partitions to a specific directory (known as the mount point) in the file system tree.
Here is an example of mounting a specified partition to the /mnt directory:
sudo mount /dev/sdc1 /mnt/
Useful options:
- mount -a - mount all filesystem mentioned in fstab file (/etc/fstab).
- mount -r - mount the filesystem as read-only.
- mount -w - mount the filesystem as read-write.
- mount -o - allows you to specify mount options.
- mount -t - used to indicate the filesytem type.
vmstat
vmstat (Virtual Memory Statistics) is a command-line utility in Linux that provides reports about various system resources such as processes, memory, paging, block IO, traps, and CPU activity.
Example:
vmstat
Useful options:
- a - Show active and inactive memory statistics.
- d - Display detailed disk statistics.
- D - Display a more detailed disk statistics table.
- f - Display the number of forks since boot. Useful to know the number of process creations.
- m - Display slab (kernel data structures) statistics.
- n - With this option, vmstat will only display the header once, at the top. By default, the header is displayed after every screen full of data.
- r - Display memory page statistics related to how many pages are paged in and out.
- s - Provide a table of event counts and memory statistics, offering a summary of key performance metrics since boot.
- t - Add a timestamp to the output. This can be helpful when monitoring system performance over extended periods.
- w - Use a wide output mode. This is especially useful on systems with many CPUs or disks, ensuring all data fits on the screen.
echo
The echo command is a built-in Linux command-line utility used to print arguments it receives to the standard output (by default your terminal display).It can also be used to display the values of user-defined variables and environment variables.
Here is an example of printing the text “Hello Linux folks!” on the terminal screen:
echo “Hello Linux folks!”
Useful options:
- n: Do not output the trailing newline.
- e: Enable interpretation of backslash-escaped characters.
- E: Disable interpretation of backslash-escaped characters (default behavior).
history
The history command is a Linux builtin command used to view and manage a list of previously executed commands in a terminal session. It provides a history of commands that have been priviously executed or entered, making it easier to recall and reuse them without typing them again.
Example:
history
Useful Options:
- c - Clears the entire command history.
- d offset - Deletes the history entry at a specific position offset.
- a - Appends the current session to the history file.
- n - Reads all history lines not already read from the history file into the current session's history.
- r - Reads the history file and appends its contents to the current session's history.
- w - Replace the content of the history file with your current session history.
- p arg [arg ...] - Performs history substitution on the following arguments and displays the result. It doesn’t save the result to the history list.
- s arg [arg ...] - Adds the arguments as a single entry in the history list.
passwd
The passwd command is used in Linux to change the user account password. If the command is used by the root user, it can change the password for other users.
Simply typing passwd without any arguments would change the currently logged-in user's password.
Here is an example:
passwd
Useful passwd command options you should be aware of:
- passwd -d - Delete a user's password (make it empty). This is the same as disabling a password for an account.
- passwd -e - Immediately expire an account's password.
- passwd -l - lock and unlock user accounts. Locking prevents the user from logging into the system and unlocking restores it.
sudo
The sudo command or superuser do in full is a Linux command that enables other users to execute commands or to perform administrative tasks on a system with superuser privileges.
Here is an example of using the sudo command to run the netstat command with superuser permissions
sudo netstat -tunlp
This command is used to check all listening ports or ports that are in use on a Linux system.
Here are some handy sudo options:
- sudo -i - switch to an interactive root session.
- sudo -D - run the command in the specified directory instead of the current working directory.
- sudo -l - lists the commands that the current user can execute with sudo privileges.
- sudo -A - forces sudo to use a graphical password prompt.
usermod
The usermod is used to modify user account attributes and settings. It has options to change various properties of an existing user account, such as their username, home directory, group membership, shell,etc.
The following is an example of using the usermod command to add the user “jay” into the sudoers file.
sudo -aG sudo jay
Here are some of the options you can use with the usermod command:
- m - Move the users home directory.
- d - Specify new home directory location. Commonly used with -m option to move a user's home direction to a new location.
- g - change the users primary group
- G - Specify the supplementary group a user member of.
- a - Add user to the group specified by -G.
- l - Rename user account.
- L - Lock user account.
- U - Unlock user account.
- e -Set user account expiration date.
- c -Set a new value for the comment field.
- s - Change the current shell.
- p - Set an encrypted password for the user account.
useradd
The useradd command a Linux used to create or add new accounts on the system. When creating users, the useradd command gives you more control via many command line options. If you are someone who wants something simple, and interactive, with a guide process then you adduser command is your go-to.
Here is an example of creating a new user without a login shell:
sudo useradd -d /path/to/home/directory -s /bin/false tom
Here are some invaluable useradd options:
- c - allows you to add a description or comment for the user.
- s - allows you to specify the login shell for the user.
- e - allows to set an expiration date for the new user.
- p - set password for new user.
- m - create a user's home directory in the default location (usually under /home) if it doesn't exist.
userdel
Once you have created a new user account there are times when you would want to delete it. Fortunately, in Linux, there is an easy way to do that using userdel command. As the name suggest, the userdel is used to delete a user account and its related files.
Here is an example of deleting the user we created earlier name tom:
sudo userdel tom
Useful userdel options:
- r - Remove the user’s home directory and mail spool along with the username.
- f - Forcefully remove the user account, even if the user is still logged in or if there are running processes that belong to the user.
- z - Remove the users SELinux user mapping.
groupadd
In Linux, the groupadd command is used to create a new group on the system. This group is known as the secondary group and you can add users to it using the usermod command. In case you don’t know, a group is a collection of user accounts that share a common set of permissions or access rights.
To create a group named developers using the usermod command you would run:
sudo groupadd developers
groupadd options breakdown:
- g - Specify the group ID (GID) manually. If not provided, the GID is taken from the system-defined range.
- o - This option allows you to create groups with a GID that is already in use.
- p - Sets the password for the new group. This is rarely used, as group passwords are considered a security risk.
- r - Create a system group. These groups are usually used for system-related tasks.
- K - Overrides default values in /etc/login.defs.
- f - This will force the command to create a group even if it already exists. If the group does not exist, the -f option has no effect.
groupmod
groupmod command in Linux is used to modify an existing group's attributes. It allows you to change the name or Group ID (GID) of a group and other related attributes.
Following is a example of changing the group name developers to devs using the groupmod command:
groupmod -n devs developers
groupmod options breakdown:
- g -This option is used to change the group's numeric ID to GID. The value must be unique, unless you use the -o option.
- n - This is used to change the group name from GROUP to NEW_GROUP. Ensure the new group name does not conflict with any existing group.
- o - Allows using a non-unique GID. This option is a modifier to the -g option.
- p - Allows you to set or change the password for the named group. The PASSWORD is encrypted using the crypt(3) function. The group password is generally not recommended to be set due to security concerns, usability issues, and overhead - considered a legacy concept.
- R - Those are options that change a group CHROOT directory. When a group CHROOT_DIR is set, the groupmod command performs modifications only in the defined CHROOT directory instead of the real one.
- P - This option updates where a group gets the files corresponding to /etc. By default, groups get these files from /etc itself, but it can be customized.
w
The w command displays information about the currently logged-in users on a system. It provides a list of users who are logged into the system, along with additional details such as their terminal, login time, idle time, the IP address they are connected from, etc.
Here is an example:
w
When you run the w command without any options, it diplays the current time, total system running time, number of users currently logged in, and average system load for the past 1, 5, and 15 minutes.
w command options:
- h - Suppresses the header in the output. This means columns names like "USER", "TTY", etc., will not be displayed.
- u - Ignores the username while determining the current process and idle time. Without this option, w will show the process and idle times for the user running the command. With -u, w will show the times for the actual owner of the TTY.
- s - Produces a shorter output format. Some columns like the JCPU, PCPU, and WHAT columns will be removed.
- -f - Toggles the FROM (remote host) field in the output. By default, this field is displayed. Using -f hides this column.
- o - Produces an old-style output format, which can be slightly different from the default. This might be useful for those familiar with older versions of the w command or when parsing with certain scripts expecting the old format.
- i - Display the IP address in the FROM field instead of the hostname (depends on version and distribution, as some versions may not support this).
ssh
The ssh command in Linux is used to establish secure remote connections between servers or remote computers over the internet. SSH or Secure Shell in full, provides a secure and encrypted method for logging into and managing remote systems.
For example, to connect to a remote server with the IP address 192.168.1.77 using the username "tom" you would use the following command:
You will be prompted to provide the password for the user tom for authentication.
Here are some important ssh command-line options:
- ssh -p - allows you to specify the ssh port to connect to the remote host.
- ssh -C - used for data compression.
- ssh -4 - forces ssh to use IPv4 addresses only.
- ssh -6 - forces ssh to use IPv6 addresses only.
- ssh -b - used to bind source addresses.
top
top is a command-line utility that displays real-time information about the processes that are running on the system. They also display the system summary, which includes memory usage. The top command not only displays the information, but also allows the user to interactively control its behavior, sort the display, and send signals to processes.
Simply typing top without any options into your terminal will start it:
top
top command-line options:
- d - Changes the refresh interval in seconds.
- b - Runs top in batch mode, which could be useful for sending output from top to other programs or to a file. In this mode, it doesn't require a terminal to run.
- c - This option tells top to display the full command path and command line arguments of the processes.
- u - Monitor all processes owned by a specific user.
- p - Monitor only specific processes, specified by their process IDs (PIDs).
- i - Do not display idle tasks.
ps
The ps command, short for "process status," is used in UNIX and UNIX-like operating systems to view information about processes running in a system. It provides you insights into the system's process activity.
Running the ps command without any options will display a basic list of processes that are associated with the terminal from which the command is executed. Here is an example:
ps
Commonly used ps command options:
- A, -e: Display information about all processes.
- f: Provide a full-format listing.
- l: Display long format.
- u user: Display processes owned by the user.
- x: Include processes not attached to a terminal.
- o format: User-defined format.
- p PID: Display information for a specific process ID (or list of PIDs).
- T: Display information about processes and threads.
bg
The bg command short for background is used to move a currently running job or a foreground process into the background. When you run a command in the foreground, it typically blocks the terminal, meaning you cannot run other commands until it is complete. The bg command allows you to change this behavior by moving a foreground process to the background, thereby freeing up the terminal for other tasks.
To move a running foreground process to the background:
First, suspend the process by using the Ctrl+Z shortcut. Then finally, you move the stopped process to the background by typing bg.
The bg command is straightforward and does not provide many options. Here is the options you should be aware of:
- bg job_spec - specifies the job or jobs you want to move to the background.
fg
The fg command in Linux is used to bring a background job or process back to the foreground, allowing you to interact with it directly in the terminal.
Here is an example of putting the current background process to the foreground using fg command:
fg
Like the bg command, the fg command also does not provide many options. Here is the only option you need know:
- fg job_spec - specifies the job or jobs you want to move to the foreground.
kill
The kill command is a powerful tool for managing processes in Linux, and it's often used in conjunction with other commands like ps, pidof or pgrep to identify the process by name or other attributes and then send signals to it using kill.
Here is an example of using the kill command and pgrep to kill a Firefox process:
kill -9 $(pgrep firefox)
kill command options:
- s - Used to specify the signal name.
- n - Used to specify the signal name
- l - list the signal names
- L - the synonym for -l
nice
The nice command in Linux is used to manage process priorities. By default, processes run at a niceness of 0. The nice command can be used to start a process with a user-defined scheduling priority. If a process is given a higher priority, the kernel will allocate more CPU time to that process.
Following is an example of using the nice command to set the niceness to 5:
sudo nice -5 tar -czf linuxuser.tar.gz ./Documents/*
The nice command does come with too many options, here are a few you should know:
- n, --adjustment=N - N-fold increase in niceness (default 10)
- --help - Display the help menu
- --version - print the version information, then quit
fuser
The fuser command in Linux is used to identify processes that are using specific files, sockets, or file systems. It is commonly employed to identify processes that are accessing or locking a specific file, especially when there's a need to edit, save, or delete that file without interference
Here is an example of identifying all processes that are accessing the file /usr/bin/python3:
fuser /usr/bin/python3
Useful fuser command-line options:
- a -Display information about the specified files whether or not they are being accessed.
- c - Treats the argument files as mount points or block devices.
- k - Kill the processes accessing the file.
- i - Ask for confirmation before killing a process.
- I - Display processes accessing specific inodes.
- l - List available signal names.
- m - Displays the PIDs of processes accessing the specified mount point or block device.
- s - Silent operation; no error messages will be displayed.
- u - Display the user IDs associated with the processes.
- v - Verbose mode for more detailed information.
- w - Access for writing; show only processes that would be prevented from writing to the specified files or filesystems.
ip
The ip command is a versatile tool in Linux for managing network configuration. It comes preinstalled in all modern Linux Distributions - part of the iproute2 package. This package replaces old tools such ifconfig, route etc. The ip command is commonly used to manage IP addresses, network interfaces, routes, ARP cache, and tunnels.
To display IP addresses for all available network interfaces you would run:
ip addr show
The following are options you can use with the ip command to modify its behavior:
- a - Executes specified command over all objects
- d - Output more detailed information
- j - Displays the output in JSON format
- p - Adds indentation to the JSON output for readability
- s - Display extra statistics -6 Instructs IP to display only IPv6 Addresses
- h - Output statistics with human readable values
- c - Enable colored output
- t - Display timestamps in the output -br Print only basic information in a tabular format
ping
ping, also known as Packet Internet Groper, a command-line utility that uses Internet Control Message Protocol (ICMP) packets to collect local network statistics. This command is part of the iputils-ping (iputils) package, which is pre-installed on all Linux distributions, and other operating systems.
To send 3 ICMP packets to google.com, for example, run the following command:
ping -c google.com
ping command options:
- a - plays a sound for each response to make an audible ping.
- f - floods network with ping responses.
- i - specifies the time interval between responses.
- I - specifies the interface to use for the requests.
- q - shows a summary of the responses.
- D - adds a timestamp to the ping output.
- T - sets TTL for the ping request.
- w - specifies the time interval before the ping command exits.
- W - displays the total time on the command execution.
- c - sends a specified number of packets.
curl
The curl command is an indispensable and versatile command for making HTTP requests. curl provides a comprehensive set of features to simplify the process of fetching data from a remote server, interacting with APIs, or debugging network issues.
Here is an example of fetching HTML content from a website by simply typing the curl command followed by the URL without any options:
curl https://jsonplaceholder.typicode.com/
Common curl command options:
- d, --data - HTTP POST data
- f, --fail - Fail fast with no output on HTTP errors
- h, --help - Get help for commands
- 1, --include - Include protocol response headers in the output
- -output - Write to file instead of stdout
- 0, --remote-name - Write output to a file named as the remote file
- -silent - Silent mode
- T, --upload-file - Transfer local FILE to destination
- user:password - Server user and password
- A, --user-agent - Send User-Agent to server
wget
The wget command in Linux is a non-interactive command-line utility that allows you to download files from the internet. wget supports various network protocols, such as HTTP, HTTPS, FTP, and etc.
To download file with wget, simply provide the url to the file as an argument. For example:
wget https://files.phpmyadmin.net/phpMyAdmin/5.1.1/phpMyAdmin-5.1.1-all-languages.zip
Useful wget command options:
- O - Downloads a file using a different file name
- b or --background - Downloads a file in the background and frees up the terminal
- i, --input-file - Allows to specify a list of URLs in a file to download.
- c - Resumes download of a partially downloaded file
- P - Specifies the directory that a file will be downloaded
- r or --recursive - Tell wget to follow links and download recursively.
scp
SCP short for secure copy protocol is a file transfer network protocol that makes it simple and safe to copy files between two remote computers or between a remote computer and a local computer. SCP makes use of the SSH (Secure Shell) protocol for authentication and encryption, ensuring that the information transmitted is secure from malicious actors.
In this example, we'll use the scp command to transfer the file log.txt to a specified remote user's home directory. In this case, the remote user is 'linux':
scp log.txt linux@remote-hostname-or-ip:/home/linux
scp command options:
- 3 - route the traffic through your machine.
- 4 - forces scp to use IPv4 addresses only.
- -6 - forces scp to use IPv6 addresses only.
- A - allows SSH-agent to be forwarded to a remote system.
- B - Selects batch mode (prevents asking for passwords or passphrases).
- C - Enable data compression when transferring files.
- c - Selects the cipher to be used to encrypt the data transfer.
- l - Limits the available bandwidth in Kbit/s.
- O - Use the legacy SCP protocol for file transfers instead of the SFTP protocol.
- P - specify a port if SSH on the remote server is set to listen on a different port other than the default port 22
- p - preserve file attributes such as the modification times, access times, and file mode bits of the original files
- q -Quiet mode: disables the progress meter as well as warning and diagnostic messages from
- r - Recursively copy a directory and its subdirectories
rsync
The rsync command in Linux is a powerful utility for efficiently copying and synchronizing files and directories between different locations via any remote shell program, or to and from a remote rsync daemon. It's commonly used to perform backups, transfer files between systems, and keep data synchronized.
To transfer a file or sync files to another directory within the local machine, you would run:
rsync -av /home/linux/backup.sh /home/linux/projects/
rsync command Options:
- a, --archive - Archive mode works similarly to the recursive mode (-r), but it maintains all file permissions, file ownership, symbolic links and so on.
- z, --compress - Used to compress file data during the transfer.
- h, --human-readable - Output numbers in a human-readable format
- b, --backup - Make backups during file transfer
- -n, --dry-run - Instruct rsync to perform a trial run that does not make any changes. It is commonly used when deleting source files or in conjunction with the verbose (-v) option to see what the rsync command will accomplish before running it.
- r, --recursive - Instructs rsync to copy a directory and its subdirectories recursively.
- -progress Show progress during transfer. This displays the amount of data transferred, the transfer speed, and the time left for the transfer to complete.
- -v, --verbose - This option increases the amount of data logged by the rsync daemon during its initial phase.
- q, --quiet -This option reduces the amount of data you receive during the transfer by suppressing information messages from the remote server. This option is useful when using cron to execute rsync.
ss
The Socket Statistics (ss) command in Linux displays network socket information.With ss, you can view detailed information about the sockets that are being used by your system, including their state, source and destination addresses, and other related information.
As an example, you can list all listening and non-listening network connections using the ss command followed by the -a or -all option:
ss -a
ss provides a lot of options to modify its behavior, here are a few:
- h - Displays a list of all options.
- V - Displays the version information.
- n - Service names are not resolved.
- r - Host names are resolved
- a - Displays all sockets
- l - Displays all listening sockets
- o - Displays timer information
- e - show detailed socket information
- m - show socket memory usage
- p - show process using socket
- i - show internal TCP information
find
Linux find command is a powerful tool that allows system administrators to search for and manage files and directories that match a set of criteria in the filesystem. You can not only use the find command to search for files on your system, but you can also use external commands to perform actions on those files, such as deleting, checking permissions, etc.
Here is an example of using the find command to find big files taking too much space on your system so you can delete them:
find / -type f -size 35000k -exec rm -i {} \;
find command options:
- name - Search by file name.
- iname - Search by filename but ignore case.
- type - Search by file type.
- size - Search by file size.
- mtime - Search by file modification time.
- exec - Execute specific command for file match.
- user - Search file by a specific user.
- group - Search file that belongs to the group.
- perm - Search file by permission.
- maxdepth - Limit the depth of find explores.
grep
The grep (Global Regular Expression Print in full) is one of the most used and powerful commands in Linux for searching and matching text patterns within one or more files. grep makes use of regular expressions to create advanced patterns for matching text in files.
To search for a pattern “Linux” in a single file called data.txt, run:
grep “Linux” data.txt
Useful grep command options:
- n - Display matching lines along with the line number.
- w - Match with the exact word.
- i - Tell grep to ignore case.
- E - Tell grep to add support for the extended regular expression.
- r or -R - Recursive search. The capital R does the same but follows the symlinks.
- q - Suppress the output.
- v - Display non-matching lines. -l Print only the matching file names.
- e - Match multiple patterns.
- f - Search patterns from a file.
- b - Display byte offset of the match.
- c - Display the count of matching lines.
- o - Display only the matching parts of a line.
- b - Tell grep to treat the binary file as a normal text file.
- A, -B, and -C - Context-based searching - after, before, and context respectively.
strings
The strings command is used in Linux to extract printable strings from binary or non-text files. It scans the files to search for sequences of readable characters. It is commonly used to examine executable files and libraries to fetch readable function and variable names, error messages, and embedded strings.
Let’s look at a basic example of using strings to examine a binary called ping:
strings ping
Some strings option:
- n or --bytes=N - specifies the minimum number of characters that a string must contain to be printed.
- t or --radix=d - Print the offset within the file before each string.
- o or --output - allows you to specify an output file to which the extracted strings will be written.
- f - Print the name of the file before each string.
- w - allows strings to include all whitespace characters in the output.
tr
The tr command, which stands for translate, is a Linux tool that can translate, squeeze, or delete characters supplied from the standard input (STDIN) and output the results to your terminal screen, which is the standard output (STDOUT).
Let's take a look at a quick example of replacing characters or letters in standard input (STDIN) by mapping the characters to be replaced (SET1) with the characters that will replace them (SET2).
echo "Linux is so amazing, that I can't live without it :d." | tr "abcd" "ABCD"
From the command each occurrence of 'a' in the standard input is replaced with A, b with B, c with C and so on.
The following are some of the most important tr options:
- c, -C, or—complement - this option changes the behavior of tr to use the complement of SET1. In other words, it will replace all characters not found in SET1.
- d or –delete - tells tr to remove the characters listed in SET1.
- s - replaces each series of a repeated character that is in the last SET with a single instance of the repeated character.
- t - instructs tr to first truncate SET1 to the length of SET2 before proceeding.
cut
The cut is a Linux/Unix command line utility that removes sections of lines from files as well as piped data and prints the selected parts of lines to standard output (stdout) that is your terminal screen.
Here is a simple example of getting a single letter from a given data that is present on a specific byte position. For example, position 14:
echo "abcdefghijklmnopqrstuvwxyz" | cut -b 14
Some useful cut options:
- b (--bytes=LIST) - this indicates which byte, bytes, or range of bytes to select.
- c (--characters=LIST) - instead of select bytes you can use the option to only select the characters you want.
- d (--delimiter=DELIM) - instead of using the TAB as the default delimiter character you can specify a character (DILIM) to use as the delimiter.
- f (--fields=LIST) - together with the -d option, it is the most used option. This option allows you to select the fields you want.
- -complement - this complement the set of bytes, characters or fields you have selected. For example, it allows the cut command to display the bytes, characters, or fields except for the ones you have selected.
- s (--only-delimited) - by default, the cut display lines with no delimiter character. This option prevents the cut command from printing lines that do not contain delimiters.
uniq
uniq command is a Linux command line utility that identifies adjacent lines that are duplicated in an input file and prints unique lines to the standard output or write to an output file.
The following example only displays unique lines in a file called example.txt:
uniq -q example.txt
uniq command line options you should be aware of:
- u, - -unique - The unique lines will only be printed from the input content.
- d, - -repeated - The duplicate lines will only be printed from the input content where it displays one line per each repeated line.
- c, - -count - Displays the duplicate count of each repeated line as a number before the line.
- D, - -all-repeated - Only outputs all the duplicated lines and ignores unique lines.
- z, - -zero-terminated A line will end with a NULL or 0 bytes. By default, each line ended with a new line.
tee
The Linux tee command is a powerful and useful command used to read from standard input and write the output to both standard output and one or more files. It's named after the T-splitter used in plumbing, which divides water into two streams, one flowing to the tap and the other to the drain.
To display the output of a specific command at the same time while writing it to a file you would run:
dh -f | tee file1.txt
tee command options:
- a or --append -Append to files instead of overwriting.
- i or --ignore-interrupts - Ignore interrupt signals.
awk
Awk is a command-line utility as well as a scripting language that is used to manipulate data and format output reports. This command supports several variables, functions, and logical operators to get the desired output.
Let’s look at a simple example of displaying a specif column in a file:
awk ‘{print $2}’ records.txt
This example will print all the records in second column.
Here are a few options that comes with awk:
- F - Specifies the field separator (delimiter) for input data.
- v var=value - Assigns a value to an awk variable.
- f scriptfile - Reads awk commands from a script file.
sed
The Linux sed command is a stream editor that is used to process text file content like searching for patterns, finding and replacing, insertion, and deletion.
To simply replace a string in a file, for example, you would run:
sed 's/World/Folks!/' example.txt
This will replace the first occurrence on the world World with Folks.
The sed command comes with a few options listed below:
- n - Suppress the automatic printing of lines
- i - Write or Modify the original file
- e - Make multiple selections where you can write multiple expressions to select multiple pieces from the text content.
sort
sort command is a Linux utility that allows you to sort lines of text files alphabetically or numerically. It is often used with other commands, such as grep and uniq, to analyze and manipulate text data. The sort command assumes data is in the ASCII format.
For example, to sort a file you would run:
sort example.txt
sort command options:
- b - ignores leading whitespace characters when sorting.
- f - performs a case-insensitive sort.
- n - sorts according to string numerical value.
- r - reverses the sorting order, making it descending.
- u - removes duplicate lines, only showing unique lines.
- o - writes the sorted output to a specified file instead of the standard output.
xargs
xargs is an oddest yet versatile Linux utility that allows you to pass the output of one command to another, allowing commands like ping, mkdir, and rm to accept standard input as arguments. It is typically used in conjunction with other commands via piping.
This example uses xargs command to execute the cat command to view the contents of the files passed from the output of the ls command:
ls | xargs ls
Some of the main options of xargs command:
- 0, --null - Terminate input items with a null character instead of whitespace, and treat special characters as normal.
- t, --verbose - Print the resulting command before the execution
- n , --max-args=max-args Set the maximum number of input arguments per executed command.
- d, --delimiter=delim - Specify a custom delimiter character to separate input items instead of the default character.
- I placeholder - Replace every occurrence of placeholder with input arguments