Skip to main content

Basic Linux Commands with Examples

In this Linux cheat sheet, we cover essential commands ranging from basic to advanced. Whether you're a beginner or an experienced professional, this cheat sheet can help you work more efficiently with the Linux operating system.

1. File and Directory Operations Commands​

File and directory operations are fundamental in working with Linux. Here are some commonly used commands:

CommandDescriptionOptionsExamples
lsList files and directories-l: Long format listing
-a: Include hidden files
-h: Human-readable file sizes
ls -l: Displays files with detailed information
ls -a: Includes hidden files
ls -lh: Shows file sizes in a human-readable format
cdChange directoryN/Acd /path/to/directory: Changes to the specified directory
pwdPrint working directoryN/Apwd: Displays the current working directory
mkdirCreate a new directoryN/Amkdir my_directory: Creates a directory named "my_directory"
rmRemove files and directories-r: Remove directories recursively
-f: Force removal without confirmation
rm file.txt: Deletes "file.txt"
rm -r my_directory: Deletes "my_directory" and its contents
rm -f file.txt: Force deletes "file.txt"
cpCopy files and directories-r: Copy directories recursivelycp file.txt destination: Copies "file.txt" to destination
cp -r directory destination: Copies directory to destination
mvMove/rename files and directoriesN/Amv file.txt new_name.txt: Renames "file.txt" to "new_name.txt"
mv file.txt directory: Moves "file.txt" to the specified directory
touchCreate an empty file or update file timestampsN/Atouch file.txt: Creates an empty file named "file.txt"
catView the contents of a fileN/Acat file.txt: Displays the contents of "file.txt"
headDisplay the first few lines of a file-n: Specify the number of lines to displayhead file.txt: Displays the first 10 lines
head -n 5 file.txt: Shows the first 5 lines
tailDisplay the last few lines of a file-n: Specify the number of lines to displaytail file.txt: Shows the last 10 lines
tail -n 5 file.txt: Displays the last 5 lines
lnCreate links between files-s: Create symbolic (soft) linksln -s source_file link_name: Creates a symbolic link named "link_name" pointing to "source_file"
findSearch for files and directories-name: Search by filename
-type: Search by file type
find /path/to/search -name "*.txt": Finds all ".txt" files in the specified directory

2. File Permission Commands​

File permissions in Linux control access to files and directories. Here are commands for managing file permissions:

CommandDescriptionOptionsExamples
chmodChange file permissionsu: User/owner permissions
g: Group permissions
o: Other permissions
+: Add permissions
-: Remove permissions
=: Set permissions explicitly
chmod u+rwx file.txt: Grants read, write, and execute permissions to the owner of "file.txt"
chownChange file ownershipN/Achown user file.txt: Changes the owner of "file.txt" to "user"
chgrpChange group ownershipN/Achgrp group file.txt: Changes the group ownership of "file.txt" to "group"
umaskSet default file permissionsN/Aumask 022: Sets default file permissions to rw-r--r--

3. File Compression and Archiving Commands​

These commands help in file compression and archiving.

CommandDescriptionOptionsExamples
tarCreate or extract archive files-c: Create a new archive
-x: Extract files from an archive
-f: Specify archive file name
-v: Verbose mode
-z: Compress with gzip
-j: Compress with bzip2
tar -czvf archive.tar.gz files/: Creates a compressed archive
gzipCompress files-d: Decompress filesgzip file.txt: Compresses "file.txt" to "file.txt.gz"
zipCreate compressed zip archives-r: Recursively include directorieszip archive.zip file1.txt file2.txt: Creates "archive.zip"

4. Process Management Commands​

Linux process management commands monitor and control processes.

CommandDescriptionOptionsExamples
psDisplay running processes-aux: Show all processesps aux: Shows all processes with detailed info
topMonitor system processes in real-timeN/Atop: Displays real-time system processes
killTerminate a process-9: Forcefully kill a processkill PID: Terminates the process with the specified ID
pkillTerminate processes by nameN/Apkill process_name: Kills all processes with the given name
pgrepList processes by nameN/Apgrep process_name: Lists all processes with the name

5. System Information Commands​

These commands display system information.

CommandDescriptionOptionsExamples
unamePrint system information-a: All system informationuname -a: Displays all system information
whoamiShow the current usernameN/Awhoami: Displays the current username
dfShow disk space usage-h: Human-readable sizesdf -h: Displays disk space in a human-readable format
duEstimate file and directory sizes-h: Human-readable sizes
-s: Display total size only
du -sh directory/: Shows total size of the specified directory
freeDisplay memory usage-h: Human-readable sizesfree -h: Shows memory usage in a human-readable format
uptimeShow system uptimeN/Auptime: Displays current system uptime
lscpuDisplay CPU informationN/Alscpu: Shows detailed CPU information
lspciList PCI devicesN/Alspci: Lists PCI devices
lsusbList USB devicesN/Alsusb: Lists USB devices

6. Networking Commands​

Use these commands to manage network connections.

CommandDescriptionExamples
ifconfigDisplay network interface informationifconfig: Displays details of network interfaces
pingSend ICMP echo requests to a hostping google.com: Checks connectivity to "google.com"
netstatDisplay network connections and statisticsnetstat -tuln: Shows TCP and UDP connections
ssDisplay network socket informationss -tuln: Shows listening TCP and UDP connections
sshSecurely connect to a remote serverssh user@hostname: Initiates an SSH connection
scpSecurely copy files between hostsscp file.txt user@hostname:/path/to/destination: Copies "file.txt" to remote host
wgetDownload files from the webwget http://example.com/file.txt: Downloads "file.txt"
curlTransfer data to or from a servercurl http://example.com: Retrieves a webpage's content

7. IO Redirection Commands​

These commands handle input/output redirection in Linux.

CommandDescriptionExamples
cmd < fileInput of cmd is taken from filecat < file.txt: Displays the content of "file.txt"
cmd > fileStandard output (stdout) is redirected to fileecho "Hello" > output.txt: Writes "Hello" to "output.txt"
cmd 2> fileError output (stderr) is redirected to filels non_existent_file 2> error.log: Redirects error to "error.log"
cmd &> fileRedirects both stdout and stderr to filels &> output.log: Redirects all output to "output.log"
cmd >> fileAppends stdout to a fileecho "New line" >> file.txt: Appends "New line" to "file.txt"

8. Environment Variable Commands​

Set and display environment variables.

CommandDescriptionExamples
export VARIABLE=valueSet an environment variableexport PATH=/usr/local/bin:$PATH: Adds a directory to the PATH
echo $VARIABLEDisplay the value of an environment variableecho $PATH: Displays the PATH environment variable
envList all environment variablesenv: Displays all environment variables
unset VARIABLERemove an environment variableunset PATH: Removes the PATH variable
export -pShow all exported environment variablesexport -p: Lists all exported variables
env VAR1=value COMMANDSet an environment variable for a specific commandenv VAR1=value command: Runs a command with modified environment variables

9. User Management Commands​

Manage user accounts and groups.

CommandDescriptionExamples
whoShow who is currently logged inwho: Displays the current logged-in users
sudo adduser usernameCreate a new usersudo adduser john: Creates a new user named "john"
fingerDisplay information about usersfinger: Displays user details
lastShow the recent login historylast: Displays login history
sudo userdel -r usernameDelete a user accountsudo userdel -r john: Deletes the user "john" and their files
su - usernameSwitch to another user accountsu - john: Switches to the "john" user account
sudo usermod -a -G GROUPNAME USERNAMEAdd user to a groupsudo usermod -a -G admin john: Adds "john" to the "admin" group

10. Shortcuts Commands​

There are many shortcuts commands in Linux that can help you be more productive. Here are a few of the most common ones:

10.1: Bash Shortcuts Commands​

NavigationDescriptionEditingDescriptionHistoryDescription
Ctrl + AMove to the beginning of the line.Ctrl + UCut/delete from the cursor position to the beginning of the line.Ctrl + RSearch command history (reverse search).
Ctrl + EMove to the end of the line.Ctrl + KCut/delete from the cursor position to the end of the line.Ctrl + GEscape from history search mode.
Ctrl + BMove back one character.Ctrl + WCut/delete the word before the cursor.Ctrl + PGo to the previous command in history.
Ctrl + FMove forward one character.Ctrl + YPaste the last cut text.Ctrl + NGo to the next command in history.
Alt + BMove back one word.Ctrl + LClear the screen.Ctrl + CTerminate the current command.
Alt + FMove forward one word.

10.2: Nano Shortcuts Commands​

File OperationsDescriptionNavigationDescriptionEditingDescriptionSearch and ReplaceDescription
Ctrl + OSave the file.Ctrl + YScroll up one page.Ctrl + KCut/delete from the cursor position to the end of the line.Ctrl + WSearch for a string in the text.
Ctrl + XExit Nano (prompt to save if modified).Ctrl + VScroll down one page.Ctrl + UUncut/restore the last cut text.Alt + WSearch and replace a string in the text.
Ctrl + RRead a file into the current buffer.*Alt + *Go to a specific line number.Ctrl + 6Mark a block of text for copying or cutting.Alt + RRepeat the last search.
Ctrl + JJustify the current paragraph.Alt + ,Go to the beginning of the current line.Ctrl + KCut/delete the marked block of text.
Alt + .Go to the end of the current line.Alt + 6Copy the marked block of text.

10.3: VI Shortcuts Commands​

CommandDescription
cwChange the current word. Deletes from the cursor position to the end of the current word and switches to insert mode.
ddDelete the current line.
xDelete the character under the cursor.
REnter replace mode. Overwrites characters starting from the cursor position until you press the Escape key.
oInsert a new line below the current line and switch to insert mode.
uUndo the last change.
sSubstitute the character under the cursor and switch to insert mode.
dwDelete from the cursor position to the beginning of the next word.
DDelete from the cursor position to the end of the line.
4dwDelete the next four words from the cursor position.
ASwitch to insert mode at the end of the current line.
SDelete the current line and switch to insert mode.
rReplace the character under the cursor with a new character entered from the keyboard.
iSwitch to insert mode before the cursor.
3ddDelete the current line and the two lines below it.
ESCExit from insert or command-line mode and return to command mode.
URestore the current line to its original state before any changes were made.
~Switch the case of the character under the cursor.
aSwitch to insert mode after the cursor.
CDelete from the cursor position to the end of the line and switch to insert mode.

10.4: Vim Shortcuts Commands​

Normal Mode​

CommandDescription
iEnter insert mode at the current cursor position.
xDelete the character under the cursor.
ddDelete the current line.
yyCopy the current line.
pPaste the copied or deleted text below the current line.
uUndo the last change.
Ctrl + RRedo the last undo.
:wSave the file.
:qQuit Vim.
:q!Quit Vim without saving changes.
:wq or :xSave and quit Vim.
:s/old/new/gReplace all occurrences of β€œold” with β€œnew” in the file.
:set nu or :set numberDisplay line numbers.

Command Mode​

CommandDescription
:wSave the file.
:qQuit Vim.
:q!Quit Vim without saving changes.
:wq or :xSave and quit Vim.

Visual Mode​

CommandDescription
vEnter visual mode to select text.
yCopy the selected text.
dDelete the selected text.
pPaste the copied or deleted text.

11. tmux - Terminal Multiplexer​

tmux is a terminal multiplexer that allows you to manage multiple terminal sessions within one window. It’s great for running multiple programs simultaneously and for managing long-running processes.

Basic tmux Commands​

CommandDescriptionExamples
tmuxStart a new tmux sessiontmux: Starts a new tmux session
tmux new-session -s session_nameStart a new tmux session with a specific nametmux new-session -s my_session: Starts a new session named "my_session"
tmux attach -t session_nameAttach to an existing tmux sessiontmux attach -t my_session: Attaches to the session named "my_session"
tmux lsList all tmux sessionstmux ls: Lists all available tmux sessions
tmux kill-session -t session_nameKill a specific tmux sessiontmux kill-session -t my_session: Kills the "my_session" tmux session
tmux detachDetach from the current tmux sessionPress Ctrl + b, then d: Detaches from the current session
tmux kill-sessionKill the current tmux sessiontmux kill-session: Kills the current session

Window and Pane Management​

  • Windows: Each tmux session can have multiple windows (like tabs in a browser).
  • Panes: Each window can be split into multiple panes (like dividing your terminal screen).
CommandDescriptionExamples
Ctrl + b cCreate a new windowCtrl + b c: Creates a new window in the current session
Ctrl + b nSwitch to the next windowCtrl + b n: Switches to the next window
Ctrl + b pSwitch to the previous windowCtrl + b p: Switches to the previous window
Ctrl + b 0-9Switch to a specific windowCtrl + b 2: Switches to window 2
Ctrl + b wList all windowsCtrl + b w: Lists all windows in the session
Ctrl + b %Split the current window verticallyCtrl + b %: Splits the window into two vertical panes
Ctrl + b "Split the current window horizontallyCtrl + b ": Splits the window into two horizontal panes
Ctrl + b oSwitch between panesCtrl + b o: Moves to the next pane
Ctrl + b xClose the current paneCtrl + b x: Closes the current pane
Ctrl + b {Move the current pane leftCtrl + b {: Moves the current pane to the left
Ctrl + b }Move the current pane rightCtrl + b }: Moves the current pane to the right

Session and Window Management​

CommandDescriptionExamples
Ctrl + b dDetach from the sessionCtrl + b d: Detaches from the session and leaves it running in the background
Ctrl + b &Close the current windowCtrl + b &: Closes the current window
Ctrl + b ,Rename the current windowCtrl + b ,: Renames the current window to a new name
Ctrl + b sList all sessionsCtrl + b s: Lists all active tmux sessions
Ctrl + b lList the last windowCtrl + b l: Switches to the last active window

Resizing Panes​

You can resize tmux panes to allocate more space for one particular pane.

CommandDescriptionExamples
Ctrl + b :Enter command modeCtrl + b :: Enter command mode to type tmux commands
resize-pane -DResize pane downCtrl + b :resize-pane -D: Shrinks the pane downward
resize-pane -UResize pane upCtrl + b :resize-pane -U: Shrinks the pane upward
resize-pane -LResize pane leftCtrl + b :resize-pane -L: Shrinks the pane left
resize-pane -RResize pane rightCtrl + b :resize-pane -R: Shrinks the pane right

Saving and Restoring Sessions​

You can save your tmux sessions and restore them later.

CommandDescriptionExamples
tmux save-buffer /path/to/fileSave the buffer contents to a filetmux save-buffer output.txt: Saves the buffer to a file named "output.txt"
tmux load-buffer /path/to/fileLoad content from a file into the buffertmux load-buffer output.txt: Loads content from "output.txt" into the tmux buffer

Copy and Paste Mode​

You can enter copy mode in tmux to scroll through the terminal output and copy text.

CommandDescriptionExamples
Ctrl + b [Enter copy modeCtrl + b [: Enter copy mode
Up/Down ArrowScroll through the terminal outputUse the arrow keys to scroll through the terminal
SpaceStart selectionSpace: Starts selecting text
EnterCopy selected textEnter: Copies the selected text
Ctrl + b ]Paste the copied textCtrl + b ]: Pastes the copied text into the current pane

These are some of the basic and advanced tmux commands that will help you get started with terminal multiplexing. You can create, manage, and navigate between multiple terminal sessions with ease, making tmux an invaluable tool for anyone working in the terminal.

Conclusion​

In conclusion, Linux is a widely used operating system for development, and as a developer, you should have knowledge of Linux and its basic commands. In this Cheat Sheet, we covered all commands like creating directories, file compression and archiving, process management, system information, networking, and more. In addition to that, this Linux Cheat Sheet is organized and categorized, making it easy for developers to quickly find the commands they need for specific use cases. By utilizing this resource, developers can enhance their productivity and efficiency in working with Linux, leading to smoother and more successful development projects.