Skip to main content

From StationX.net

Essential Commands

We recommend that you memorize these commands. You’ll need them the most when operating Linux.

File Management

In the following commands: X may refer to a single file, a string containing a wildcard symbol referring to a set of multiple files, e.g., file*.txt, or the stream output of a piped command (in which case the syntax would be X | command instead of command X); Y is a single directory; A and B are path strings of files/directories.

COMMANDDESCRIPTION
*Wildcard symbol for variable length, e.g., *.txt refers to all files with the TXT extension
?Wildcard symbol referring to a single character, e.g., Doc?.docx can refer to Doc1.docx, DocA.docx, etc.
lsList the names of files and subfolders in the current directory. Options include -l, -a, -t which you may combine, e.g., -alt.
ls -lAlso show details of each item displayed, such as user permissions and the time/date when the item was last modified
ls -aAlso display hidden files/folders. May be combined with ls -l to form ls -al.
ls -tSort the files/folders according to the last modified time/date, starting with the most recently modified item
ls X List the files 
cd YChange directory to Y.

Special instances of Y:
.  — current directory
.. — parent directory
cdTo the $HOME directory
cd ..Up one level to enclosing folder or parent directory
cd /etcTo the /etc directory
cmp A BCompare two files A and B for sameness. No output if A and B are identical, outputs character and line number otherwise.
diff A BCompare two files A and B for differences. Outputs the difference.
pwdDisplay the path of the current working directory.
mkdir XMake a new directory named X inside the current directory.
mv A BMove a file from path A to path B. Also used for renaming files.
Examples:
– Moving between directories folder1 and folder2:
mv ./folder1/file.txt ./folder2
The file name will remain unchanged, and its new path will be ./folder2/file.txt.
– Renaming a file: mv new_doc.txt expenses.txt
The new file name is expenses.txt.
cp A BCopy a file from path A to path B. Usage similar to mv both in moving to a new directory and simultaneously renaming the file in its new location.
Example: cp ./f1/file.txt ./f2/expenses.txt simultaneously copies the file file.txt to the new location with a new name expenses.txt.
cp -r Y ZRecursively copy a directory Y and its contents to Z. If Z exists, copy source Y into it; otherwise, create Z and Y becomes its subdirectory with Y’s contents
rm XRemove (delete) X permanently.
rm -r YRecursively delete a directory Y and its contents
rm -f XForcibly remove file X without prompts or confirmation
rm -rf YForcibly remove directory Y and its contents recursively
rmdir YRemove a directory Y permanently, provided Y is empty.
open XOpen X in its default program.
open -e XOpens X in the default text editor (macOS: TextEdit)
touch XCreate an empty file X or update the access and modification times of X.
cat XView contents of X.
cat -b XAlso display line numbers as well.
wc XDisplay word count of X.
head XDisplay the first 10 lines of X. If more than a single file is specified, each file is preceded by a header consisting of the string “==> X <==” where “X” is the name of the file.
head -n 4 XShow the first 4 lines of X.
ls *.c | head -n 5Display the first 5 items of a list of *.c files in the current directory.
tail XDisplay the last (10, by default) lines of X. If more than a single file is specified, each file is preceded by a header consisting of the string “==> X <==” where “X” is the name of the file.
tail -n +1 XDisplay entire contents of the file(s) X specified, with header of respective file names
tail -f XDisplay the last 10 lines of the file(s) X specified, and track changes appended to them at the end. Overwriting X or modifying X with a text editor such as vim would mess up this command’s output.
lessRead a file with forward and backward navigation. Often used with pipe, e.g., cat file.txt | less
ln -s A SCreate symbolic link of path A to link name S.

Input/Output Redirection

These are helpful for logging program output and error messages.

COMMANDDESCRIPTION
echo TEXTDisplay a line of TEXT or the contents of a variable.
echo -e TEXTAlso interprets escape characters in TEXT, e.g., \n → new line, \b → backslash, \t → tab.
echo -n TEXTOmits trailing newline of TEXT.
cmd1 | cmd2| is the pipe character; feeds the output of the command cmd1 and sends it to the command cmd2, e.g., ps aux | grep python3.
cmd > fileRedirect output of a command cmd to a file file. Overwrites pre-existing content of file.
cmd >& fileRedirect output of cmd to file. Overwrites pre-existing content of file. Suppresses the output of cmd.
cmd > /dev/nullSuppress the output of cmd.
cmd >> fileAppend output of cmd to file.
cmd < fileRead input of cmd from file.
cmd << delimRead input of cmd from the standard input with the delimiter character delim to tell the system where to terminate the input. Example for counting the number of lines of ad-hoc input:
wc -l << EOF
> I like > apples > and > oranges. > EOF      
 4
Hence there are only 4 lines in the standard input delimited by EOF.
cmd <<< stringInput a text string to cmd.
cmd 2> fooRedirect error messages of cmd to foo.
cmd 2>> fooAppend error messages of cmd to foo.
cmd &> fileRedirect output and error messages of cmd to file.

Search and Filter

These commands help you find the files you want.

COMMANDDESCRIPTION
grep patt /path/to/srcSearch for a text pattern patt in X. Commonly used with pipe e.g., ps aux | grep python3 filters out the processes containing python3 from all running processes of all users.
grep -r patt /path/to/srcSearch recursively (the target directory /path/to/src and its subdirectories) for a text pattern patt.
grep -v patt XReturn lines in X not matching the specified patt.
grep -l patt XWrite to standard output the names of files containing patt.
grep -i patt XPerform case-insensitive matching on X. Ignore the case of patt.
findFind files.
find /path/to/src -name "*.sh"Find all files in /path/to/src matching the pattern “*.sh” in the file name.
find /home -size +100MFind all files in the /home directory larger than 100MB.
locate nameFind files and directories by name.
sort XArrange lines of text in X alphabetically or numerically.

Archives

These commands are for unpacking compressed files (.zip, .gz, .bz2, .tar, etc.) with large or complex contents, such as programs.

COMMANDDESCRIPTION
tarManipulate archives with .tar extension.
tar -vGet verbose output while manipulating TAR archives. May combine this option with others, e.g., tar -tvf.
tar -cf archive.tar YCreate a TAR archive named archive.tar containing Y.
tar -xf archive.tarExtract the TAR archive named archive.tar.
tar -tf archive.tarList contents of the TAR archive named archive.tar.
tar -czf archive.tar.gz YCreate a gzip-compressed TAR archive named archive.tar.gz containing Y.
tar -xzf archive.tar.gzExtract the gzip-compressed TAR archive named archive.tar.gz.
tar -cjf archiave.tar.bz2 YCreate a bzip2-compressed TAR archive named archive.tar.bz2 containing Y.
tar -xjf archive.tar.bz2Extract the bzip2-compressed TAR archive named archive.tar.bz2.
gzipManipulate archives with .gz extension.
gzip YCreate a gzip archive named Y.gz containing Y.
gzip -l Y.gzList contents of gzip archive Y.gz.
gzip -d Y.gz
gunzip Y.gz
Extract Y.gz and recover the original file Y.
bzip2Manipulate archives with .bz2 extension.
bzip2 YCreate a bzip2 archive named Y.bz2 containing Y.
bzip2 -d Y.gz
bunzip2 Y.gz
Extract Y.bz2 and recover the original file Y.
zip -r Z.zip YZip Y to the ZIP archive Z.zip.
unzip Z.zipUnzip Z.zip to the current directory.
unzip Z.zipList contents of Z.zip.

File Transfer

These commands are for logging in to local and remote hosts, and for uploading and downloading files, transferring them between devices. Remember to omit the square brackets “[” and “]” when you input the optional parameters they enclose.

COMMANDDESCRIPTION
ssh user@accessConnect to access as user.
ssh accessConnect to access as your local username.
ssh -p port user@accessConnect to access as user using port.
scp [user1@]host1:[path1] [user2@]host2:[path2]Login to hostN as userN via secure copy protocol for N=1,2.

Example usage:
scp alice@pi:/home/source bob@arduino:/destination

path1 and path2 may be local or remote, but ensure they’re absolute rather than relative paths, e.g., /var/www/*.html/usr/bin.

If user1 and user2 are not specified, scp will use your local username.
scp -P port [user1@]host1:[path1] [user2@]host2:[path2] Connect to hostN as userN using port for N=1,2.
scp -r [user1@]host1:[path1] [user2@]host2:[path2]Recursively copy all files and directories from path1 to path2.
sftp [user@]accessLogin to access as user via secure file transfer protocol. If user is not specified, your local username will be used.
sftp accessConnect to access as your local username.
sftp -P port user@accessConnect to access as user using port.
rsync -a [path1] [path2]Synchronize [path1] to [path2], preserving symbolic links, attributes, permissions, ownerships, and other settings.
rsync -avz host1:[path1] [path2]Synchronize [path1] on the remote host host1 to the local path [path2], preserving symbolic links, attributes, permissions, ownerships, and other settings. It also compresses the data involved during the transfer.

File Permissions

Not all files are equally accessible. To prevent unwanted tampering, some files on your device may be read-only. For more information about file permissions on Linux, refer to our Linux File Permissions Cheat Sheet.

Linux file type - regular file, d directory, l symbolic link; scope u user, g group, o other, a all; permissions r read, w write, x execute
COMMANDDESCRIPTION
chmod permission fileChange permissions of a file or directory. Permissions may be of the form [u/g/o/a][+/-/=][r/w/x] (see examples below) or a three-digit octal number.
chown user2 fileChange the owner of a file to user2.
chgrp group2 fileChange the group of a file to group2.

Usage examples:

  • chmod +x testfile → allow all users to execute the file
  • chmod u-w testfile → forbid the current user from writing or changing the file
  • chmod u+wx,g-x,o=rx testfile → simultaneously add write and execute permissions to user, remove execute permission from group, and set the permissions of other users to only read and write.

Numeric Representation

The table below compares Linux file permissions in octal form and in the format [u/g/o/a][+/-/=][r/w/x].

OCTALPERMISSION(S)EQUIVALENT TO APPLICATION OF
0No permissions-rwx
1Execute permission only=x
2Write permission only=w
3Write and execute permissions only: 2 + 1 = 3=wx
4Read permission only=r
5Read and execute permissions only: 4 + 1 = 5=rx
6Read and write permissions only: 4 + 2 = 6=rw
7All permissions: 4 + 2 + 1 = 7=rwx

Examples

  • chmod 777 testfile → allow all users to execute the file
  • chmod 177 testfile → restrict current user (u) to execute-only, while the group (g) and other users (o) have read, write and execute permissions
  • chmod 365 testfile → user (u) gets to write and execute only; group (g), read and write only; others (o), read and execute only.

System Information

These commands come in handy when you’re developing new applications for Linux or troubleshooting your Linux machine.

General

These provide information about your Linux machine and perform administrative tasks.

COMMANDDESCRIPTION
unameShow the Linux system information.
uname -aDetailed Linux system information
uname -rKernel release information, such as kernel version
uptimeShow how long the system is running and load information.
su
sudo
Superuser; use this before a command that requires root access e.g., su shutdown
calShow calendar where the current date is highlighted.
dateShow the current date and time of the machine.
haltStop the system immediately.
shutdownShut down the system.
rebootRestart the system.
last rebootShow reboot history.
man COMMANDShows the manual for a given COMMAND. To exit the manual, press “q”.
hostnameShow system host name
hostname -IDisplay IP address of host
cat /etc/*-releaseShow the version of the Linux distribution installed. For example, if you’re using Red Hat Linux, you may replace * with redhat.

Hardware

These commands provide details about the hardware supporting your Linux machine.

COMMANDDESCRIPTION
dmesgDisplay messages in kernel ring buffer (data structure that records messages related to the operation of the program running the operating system)
cat /proc/cpuinfo Display information about the central processing unit (CPU)
cat /proc/meminfoDisplay memory information
lspci -tvDisplays information about each Peripheral Component Interconnect (PCI) device on your system.
The option -t outputs the information as a tree diagram, and -v is for verbose output.
lsusb -tvDisplay information about Universal Serial Bus (USB) devices and the devices connected to them.
The option -t outputs the information as a tree diagram, and -v is for verbose output.
dmidecodeDisplay system hardware components, serial numbers, and BIOS version
hdparm -i /dev/sdaDisplay information about the disk sda
hdparm -tT /dev/sdaPerform a read speed test on the disk sda 
badblocks -s /dev/sdaTest for unreadable blocks on the disk sda

Disk Usage

These commands provide storage details regarding your Linux machine.

COMMANDDESCRIPTION
dfDisplay free disk space.
duShow file/folder sizes on disk.
du -ahDisk usage in human readable format (KB, MB etc.)
du -shTotal disk usage of the current directory
du -hFree and used space on mounted filesystems
du -iFree and used inodes on mounted filesystems
fdisk -lList disk partitions, sizes, and types
free -hDisplay free and used memory in human readable units.
free -mDisplay free and used memory in MB.
free -gDisplay free and used memory in GB.

Process Management and Performance Monitoring

The following is redolent of functions in Windows Task Manager, but on the command line.

COMMANDDESCRIPTION
&Add this character to the end of a command/process to run it in the background
psShow process status. Often used with grep e.g., ps aux | grep python3 displays information on processes involving python3.

Meaning of aux:
a = show processes for all users
u = show user or owner column in output
x = show processes not attached to a terminal
ps -e
ps -A
Either of these two commands prints all running processes in the system
ps -efPrint detailed overview
ps -U root -u rootDisplay all processes running under the account root.
ps -eo pid,user,commandDisplay only the columns piduser and command in ps output
topDisplay sorted information about processes
htopDisplay sorted information about processes with visual highlights. It allows you to scroll vertically and horizontally, so you can see every process running on your system and entire commands.
atopDisplay detailed information about processes and hardware
kill PIDKill a process specified by its process ID PID, which you obtain using the ps command
killall proc1Kill all processes containing proc1 in their names
lsofList all open files on the system. (This command helps you pinpoint what files and processes are preventing you from successfully ejecting an external drive.)
lsof -u rootList all files on the system opened by the root user. As the output can be long, you may use lsof -u root | less to keep this list from taking up space in the terminal output.
mpstat 1Display processor-related statistics, updated every second (hence the 1, whereas mpstat 2 refreshes the output every 2 seconds)
vmstat 1Display virtual memory statistics (information about memory, system processes, paging, interrupts, block I/O, disk, and CPU scheduling), updated every (1) second
iostat 1Display system input/output statistics for devices and partitions. virtual memory statistics, updated every (1) second
tail -n 100 /var/log/messagesDisplay the last 100 lines in the system logs.
Replace /var/log/messages with /var/log/syslog for Debian-based systems.
tcpdump -i eth0Capture and display all packets on interface eth0
tcpdump -i eth0 port 80Monitor all traffic on interface eth0 port 80 (HTTP)
watch df -hExecute df -h and show periodic updates.
To exit, press Ctrl+C.

User Management

These commands give information on the system’s users and allows superuser administrators to change user settings.

COMMANDDESCRIPTION
whoDisplay who is logged in
wDisplay what users are online and what they are doing
usersList current users
whoamiDisplay what user you are logged in as
idDisplay the user ID and group IDs of your current user
lastDisplay the last users who have logged onto the system
groupadd gp1Create a group named gp1
useradd -c "Alice Bob" -m ab1Create an account named ab1, with a comment of “Alice Bob” and create the new user’s home directory
userdel ab1Delete the account named ab1
usermod -aG gp1 ab1Add the account ab1 to the group gp1

Networking

These commands regulate how your Linux machine communicates with other computers, such as the local area network (LAN) router or external websites.

COMMANDDESCRIPTION
ifconfigDisplay all network interfaces with IP addresses
ifconfig -aDisplay all network interfaces, even if any of them is down, with IP addresses
ifconfig eth0Display IP addresses and details of the eth0 interface
ip aAnother way to display all network interfaces with IP addresses
ethtool eth0Query or control network driver and hardware settings of the interface eth0
netstatPrint open sockets of network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.
Pipe with the less command: e.g., netstat -a | less
netstat -aShow both listening and non-listening sockets
netstat -lShow only listening sockets
netstat -nutlpShow listening TCP and UDP ports and corresponding programs
ping hostSend ICMP echo request to host, which may be a symbolic name, domain name or IP address
whois domainDisplay whois information for domain
dig domainDisplay DNS information for domain
dig -x addrDo a reverse lookup on an IPv4 or IPv6 address addr
host domainDisplay DNS IP address for domain
wget LINKDownload from location LINK
curl LINKDisplay the HTML source of LINK. Check out our curl Cheat Sheet for details.

Installing New Programs

A package file is an archive containing compiled software and other resources it uses. The package file extension and the package installer (a utility for installing new programs) depend on the Linux distribution.

Know your system’s Linux distribution to understand the correct installation commands tailored to it. If the package comes with a README component, it should contain application-specific installation instructions such as extracting TAR files (refer to this article’s Archives section), ./setup.sh, and make install.

Package Management Overview

The following table is on package management in popular Linux distributions.

LINUX DISTRIBUTIONPACKAGE FILE EXTENSIONPACKAGE INSTALLER(S)
Debian / Ubuntu.debapt, dpkg
Rocky / Fedora / Red Hat Enterprise Linux.rpmyum, dnf
Arch Linux / Manjaro / Garuda / Chakra.pkg, .pacman, .pkg.tar(.xz/.zst/.gz)pacman

Package Management Commands

Here are the commands for package management in popular Linux distributions.

LINUX DISTRIBUTIONDEBIAN / UBUNTUROCKY / FEDORA / RED HAT ENTERPRISE LINUXARCH LINUX / MANJARO / GARUDA / CHAKRA
Update list of packages available from remote repositoriessudo apt updatednf check-updateThe command pacman -Syy achieves this purpose but may damage your system.
Use pacman -Syu instead.
Upgrade installed packagessudo apt upgradesudo dnf upgradepacman -Syu
Find a package with keyword in the nameapt search keyworddnf search keywordpacman -Ss keyword
View description and summary information about a packageapt show packagednf info packagepacman -Si package
Install a package (with appropriate file extension) on the local file systemsudo dpkg -i package.debsudo dnf install package.rpmpacman -S package
Remove / uninstall a packagesudo apt remove packagesudo dnf erase packagepacman -R package

source: https://www.stationx.net/linux-command-line-cheat-sheet/