Skip to main content

One post tagged with "Linux"

Linux blogs/tutorials

View All Tags

Linux Cheat Sheet

· 12 min read
Nabeel Hassan
Trainer @ DevOps Medium

Linux is a family of open-source Unix-like operating systems based on the Linux kernel. Linux is known for its stability, security, and flexibility, making it widely used in servers, desktops, embedded systems, and other platforms. It supports a wide range of hardware and provides a robust environment for software development and deployment.

Basic Linux Commands with Examples

This Linux cheat sheet covers all the most important Linux commands from the basics.

File Management

CommandDescriptionOptionsExamples
lsList files and directories.
-l: Long format listing.
-a: Include hidden files.
-h: Human-readable file sizes.
  • ls -l
displays files and directories with detailed information.

  • ls -a
shows all files and directories, including hidden ones.

  • ls -lh
displays file sizes in a human-readable format.
cdChange directory.
  • cd /path/to/directory
changes the current directory to the specified path.
pwdPrint current working directory.
  • pwd
displays the current working directory.
mkdirCreate a new directory.
-p: Create the parent directories as needed
  • mkdir my_directory
Creates a new directory named “my_directory”.

  • mkdir -p /path/to/my_directory
Creates a new directory named "my_directory" at specified. If the path doesn't exsist it will also be created.
rmRemove files and directories.
-r: Remove directories recursively.
-f: Force removal without confirmation.
  • rm file.txt
deletes the file named “file.txt”.

  • rm -r my_directory
deletes the directory “my_directory” and its contents.

  • rm -f file.txt
forcefully deletes the file “file.txt” without confirmation.
cpCopy files and directories.
-r: Copy directories recursively.
  • cp -r directory destination
copies the directory “directory” and its contents to the specified destination.

  • cp file.txt destination
copies the file “file.txt” to the specified destination.
mvMove/rename files and directories.
  • mv file.txt new_name.txt
renames the file “file.txt” to “new_name.txt”.

  • mv file.txt directory
moves the file “file.txt” to the specified directory.
touchCreate an empty file or update file timestamps.
  • touch file.txt
creates an empty file named “file.txt”.
catView the contents of a file.
  • cat file.txt
displays the contents of the file “file.txt”.
headDisplay the first few lines of a file.
-n: Specify the number of lines to display.
  • head file.txt
shows the first 10 lines of the file “file.txt”.

  • head -n 5 file.txt
displays the first 5 lines of the file “file.txt”.
tailDisplay the last few lines of a file.
-n: Specify the number of lines to display.
-f: It makes the command keep the file open and continuously output new lines as they are added to the file.
  • tail file.txt
shows the last 10 lines of the file “file.txt”.

  • tail -n 5 file.txt
displays the last 5 lines of the file “file.txt”.

  • tail -f file.txt
will display the last 10 lines of the "file.txt" file and then continue to display any new lines added to the file in real-time.
lnCreate links between files.
-s: Create symbolic (soft) links.
  • ln -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”
searches for all files with the extension “.txt” in the specified directory.

File Permission Commands

Each file and directory has three types of users who can interact with it:

  • Owner: The user who owns the file.
  • Group: Users who are part of the file's group.
  • Others: All other users.

Permissions are represented by three bits for each user type:

  • r: Read permission (4)
  • w: Write permission (2)
  • x: Execute permission (1)

Permissions can be set using a three-digit octal number. Each digit corresponds to the owner, group, and others, respectively.

  • 0: No permission
  • 1: Execute only
  • 2: Write only
  • 3: Write and execute
  • 4: Read only
  • 5: Read and execute
  • 6: Read and write
  • 7: Read, write, and execute
CommandDescriptionOptionsExamples
chmodChange file permissions.
u: User/owner permissions.
g: Group permissions.
o: Other permissions.
+: Add permissions.
–: Remove permissions.
=: Set permissions explicitly.
  • chmod 700 file.txt
grant full permissions (rwx) to the Owner, and no permissions for the group and others.

  • chmod -R 755 /path/to/directory
sets the permissions to rwx for the owner and rw- for the group and others for all files within the directory and subdirectories.

  • chmod u+rwx,g+rx,o+r file.txt
This command grants read, write, and execute permissions to the owner, read and execute permissions to the group, and read permission to others.

chownChange file ownership.
  • chown user file.txt
changes the owner of “file.txt” to the specified user.
chgrpChange group ownership.
  • chgrp group file.txt
changes the group ownership of “file.txt” to the specified group.
umaskSet default file permissions.
  • umask 022
sets the default file permissions to read and write for the owner, and read-only for group and others.

File Compression and Archiving Commands

CommandDescriptionOptionsExamples
tarCreate or extract archive files.
-c: Create a new archive.
-x: Extract files from an archive.
-f: Specify the archive file name.
-v: Verbose mode.
-z: Compress the archive with gzip.
-j: Compress the archive with bzip2.
  • tar -czvf archive.tar.gz files/
creates a compressed tar archive named “archive.tar.gz” containing the files in the “files/” directory.

  • tar -xzf archive.tar.gz
This extracts a gzip-compressed tar archive from “archive.tar.gz”
gzipCompress files.
-d: Decompress files.
  • gzip file.txt
compresses the file “file.txt” and renames it as “file.txt.gz”.
zipCreate compressed zip archives.
-r: Recursively include directories.
  • zip archive.zip file1.txt file2.txt
creates a zip archive named “archive.zip” containing “file1.txt” and “file2.txt”.
unzipExtract files from zip archives.
-l: List the contents of the ZIP file without extracting.
-d: Extract files into a specified directory.
-o: Overwrite existing files without prompting.
-n: Never overwrite existing files.
  • unzip archive.zip file1.zip
extracts all the contents of archive.zip into the current directory.

Process Management Commands

CommandDescriptionOptionsExamples
psDisplay running processes.
aux: Show all processes.
  • ps aux
shows all running processes with detailed information.
topMonitor system processes in real-time.
  • top
displays a dynamic view of system processes and their resource usage.
killTerminate a process.
-9: Forcefully kill a process.
  • kill PID
terminates the process with the specified process ID.
pkillTerminate processes based on their name.
  • pkill process_name
terminates all processes with the specified name.
pgrepList processes based on their name.
  • pgrep process_name
lists all processes with the specified name.
grepUsed to search for specific patterns or regular expressions in text files or streams and display matching lines.
-i: Ignore case distinctions while searching.
-v: Invert the match, displaying non-matching lines.
-r or -R: Recursively search directories for matching patterns.
-l: Print only the names of files containing matches.
-n: Display line numbers alongside matching lines.
-w: Match whole words only, rather than partial matches.
-c: Count the number of matching lines instead of displaying them.
-e: Specify multiple patterns to search for.
-A: Display lines after the matching line.
-B: Display lines before the matching line.
-C: Display lines both before and after the matching line.
  • grep -i “hello” file.txt
  • grep -v “error” file.txt
  • grep -l “keyword” file.txt
  • grep -n “pattern” file.txt
these examples will return our desired output from “file.txt”

System Information Commands

CommandDescriptionOptionsExamples
unamePrint system information.
-a: All system information.
  • uname -a
displays all system information.
whoamiView Current User
  • whoami
dfShow disk space usage.
-h: Human-readable sizes.
  • df -h
displays disk space usage in a human-readable format.
duCheck User's Disk Usage
  • du -sh /home/john
freeDisplay memory usage information.
-h: Human-readable sizes.
  • free -h
displays memory usage in a human-readable format.
uptimeShow system uptime.
  • uptime
shows the current system uptime.
lscpuDisplay CPU information.
  • lscpu
provides detailed CPU information.
lspciList PCI devices.
  • lspci
list all PCI devices connected.
lsusbList USB devices.
  • lsusb
list all connected USB devices.

Networking Commands

CommandDescriptionOptionsExamples
ipDisplay and manage networking, routing, and tunnel configurations.
addr: Diplay IP Addresses.

route: Display/Manage route table.

link: Manage network interface
  • ip addr
shows the details of all network interfaces.

  • ip route show
shows the details of Routes in Route Table.

  • ip link set dev eth0 down
brings eth0 interface down.
ifconfigDisplay network interface information.
-a: Display all Interfaces
  • ifconfig -a
shows the details of all network interfaces.
pingSend ICMP echo requests to a host.
-4: Sends ICMP request to IPv4 address of network host.
-6: Sends ICMP request to IPv6 address of network host.
  • ping google.com
sends ECHO_REQUEST to google.com

netstatDisplay network connections and statistics.
-a: Displays all connections.
-n: Show numerical addresses and ports.
-l: Shows listening ports.
-t: Shows TCP connnections information only.
-u: Shows UDP connections information only.
  • netstat
displays network connections.

  • netstat -nlt
displays only TCP listenting connections.

  • netstat -nlu
displays only UCP listenting connections.
sshSecurely connect to a remote server.
-p: Specify a Port for connection.

-i: Path of Identity (Private Key) File.

-L: Tunneling with SSH (Local port forwarding).

-R: Reverse Tunneling
  • ssh user@remote_host
stablish basic SSH connection

  • ssh -p 25 user@remote_host
stablish SSH connection on port 25

  • ssh -i /path/to/private_key user@remote_host
connects to remote host using a specific private key

  • ssh -L 8080:locahost:80 user@remote_host
Forwards all traffic send to port '8080' on local machine to remote host port '80'

  • ssh -R 9090:localhost:3000 user@remote_host
Forwards all traffic sent to port '9090' on remote host to port '3000' of local machine
scpSecurely copy files between hosts.
-r: Copy Directory recursively
  • scp file.txt user@remote_host:/path/to/destination
Copy local file 'file.txt' to remote host

  • scp user@remote_host:/path/to/file.txt /local/path
Copy file 'file.txt' from remote host to local machine

  • scp -r /local/directory/ user@remote_host:/remote/directory/
Copies an entire directory and its contents to the remote host.
wgetDownload files from the web.
-O: Download file with defined Output Filename

-A: Download only specific file types
  • wget http://example.com/file.txt
Downloads the file file.txt from the specified URL.

  • wget -O myfile.txt http://example.com/file.txt
Downloads the file and saves it as myfile.txt instead of the original filename.

  • wget -A "*.jpg,*.png" http://example.com
Downloads only .jpg and .png image files.

  • wget --user=username --password=password http://example.com/secure-file.zip
Downloads a file from a password-protected server.
curlTransfer data to or from a server.
-L: Follow Redirects

-O: Download a file

-o: Download file with defined Output Filename

-X: Change the HTTP method

-d: Send data in body of HTTP request

-H: Send headers with HTTP request

-u: Download with Authentication

-x: Download Using a Proxy

-F: Upload Binary File (e.g., ZIP file) via POST

-k: Ignore Invalid SSL Certificates
  • curl http://example.com
Sends an HTTP GET request to the specified URL and displays the response.

  • curl -L http://example.com
Follows any redirects (3xx responses) automatically.

  • curl -O http://example.com/file.txt
Downloads the file from the specified URL and saves it with the original filename.

  • curl -o myfile.txt http://example.com/file.txt
Downloads the file and saves it as myfile.txt

  • curl -X POST -d "param1=value1¶m2=value2" http://example.com
Sends a POST request with the data param1=value1¶m2=value2

  • curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://example.com
Sends a POST request with JSON data.

  • curl -u username:password http://example.com/secure-file.txt
Downloads a file using basic HTTP authentication.

  • curl -x http://proxyserver:8080 http://example.com
Send HTTP request via the specified proxy server.

  • curl -X POST -F 'file=@/path/to/file.zip' http://example.com/upload
Uploads a binary file (such as a ZIP file) via a POST request.

  • curl -k https://example.com
Ignores SSL certificate errors when making requests to HTTPS URLs.

IO Redirection Commands

NameDescriptionExamples
Standard Output Redirection> : Redirects output, overwriting the file if it exists. >> : Redirects output, appending to the file if it exists.
  • echo "Hello, World!" > file.txt
Writes "Hello, World!" to file.txt, overwriting it if it exists.

  • echo "Another Line" >> file.txt
Appends "Another Line" to file.txt.
Standard Input Redirection<: Redirects input from a file to a command.
  • cat < file.txt
Reads content from file.txt and displays it.
Standard Error Redirection2> : Redirects error output, overwriting the file. 2>> : Redirects error output, appending to the file.
  • ls /nonexistent-dir 2> error.log
Sends the error message to error.log, overwriting the file.

  • ls /another-nonexistent-dir 2>> error.log
Appends the error message to error.log.
Redirect Both Output and Error&> : Redirects both standard output and error, overwriting the file. &>> : Redirects both standard output and error, appending to the file.
  • command &> output.log
Writes both output and error to output.log.

  • command &>> output.log
Appends both output and error to output.log.
Combine Standard Output and Error2>&1: Redirects standard error to the same location as standard output.
  • ls /dir/ > output.log 2>&1
Sends both output and error to output.log.
Discard Output/dev/null: Send unwanted output or error to the null device (acts as a "black hole").
  • command > /dev/null
Ignores the output of the command.

  • command 2> /dev/null
Ignores the error output of the command.

  • command &> /dev/null
Ignores both the output and the error.
Here Document<<: Used to pass a multiline string as input to a command.
  • cat << EOF
    This is a
    multiline string
    EOF
Passes the multiline string as input to the cat command.
Here String<<<: Redirects a string as input to a command.
  • grep "Hello" <<< "Hello, World!"
Searches for "Hello" in the string "Hello, World!".
Piping|: Sends the output of one command as input to another command.
  • ls | grep "file"
Passes the output of ls to grep, searching for "file".

Environment Variable Commands

Command / NameDescriptionExamples
envDisplays all environment variables.
  • env
printenvPrints specific or all environment variables.
  • printenv PATH
Displays the value of PATH
exportTemporary Environment Variable (Only for current shell session)
  • MY_VAR="HelloWorld"
    export MY_VAR
    echo $MY_VAR
echo will return HelloWorld

Persisting Environment VariablesAdd to .bashrc or .bash_profile
  • echo 'export VAR_NAME="value"' >> ~/.bashrc
    source ~/.bashrc
Unsetting Environment VariablesRemoves an environment variable.
  • unset MY_VAR echo $MY_VAR
echo will return emtpy output
Predefined Environment Variables
NameDescriptionExamples
HomeUser's home directory
  • /home/username
USERCurrent logged-in username
  • username
PATHList of directories for executable searching
  • /usr/local/sbin:/usr/local/bin:/usr/sbin:/bin
SHELLPath to the current shell
  • /bin/bash
PWDCurrent working directory
  • /home/username/projects
LANGCurrent language setting
  • en_US.UTF-8
TERMType of terminal to emulate
  • xterm-256color
Special Variables in Shell Scripting
NameDescriptionExamples
$0The script's filename
  • script.sh
$1, $2, ...Positional parameters (arguments passed to script)
  • arg1, arg2
$#Number of arguments
  • 2
$?Exit status of the last command
  • 0 (success), non-zero (failure)
$$Process ID of the current shell
  • 12345
$@All positional parameters
  • arg1 arg2

User Management Commands

CommandDescriptionOptionsExamples
useraddCreate a new user
-d /home/USERNAME : Specify user's home directory
-m : Create the user's home directory
-s /bin/bash : Specify the login shell
-c "COMMENT" : Add a comment for the user
  • sudo useradd [OPTIONS] USERNAME


  • sudo useradd -m -d /home/john -s /bin/bash -c "John Doe" john
passwdSet or Update a User Password
  • sudo passwd USERNAME
userdelDelete a User
-r : Remove the user's home directory and mail spool
  • sudo userdel [OPTIONS] USERNAME


  • sudo userdel -r john
usermodModify an Existing User
-l NEW_USERNAME : Change the user's login name.
-d /new/home/directory : Change the user's home directory
-s /bin/sh : Change the login shell
-aG GROUP : Add the user to a group (non-destructive)
-g:Change User's Primary Group
-L: lock a user account
-L: lock a user account
  • sudo usermod [OPTIONS] USERNAME


  • sudo usermod -l john_doe john
Update 'john' username to 'john_doe'

  • sudo usermod -aG sudo john_doe
add john_doe to sudo group

  • sudo usermod -g devops john
change the default group of 'john' to 'devops'

  • sudo usermod -L john
Locks john account

  • sudo usermod -U john
Unlocks john account

groupaddCreate a new group
  • sudo groupadd GROUPNAME
  • sudo groupadd devops
suSwitch to another user
- : Start a login shell
  • su [OPTIONS] USERNAME
  • su - john
groupsList user groups
  • groups USERNAME
  • groups john
lastlogShow Last Login Information
  • lastlog -u john
whoamiView Current User
  • whoami
duCheck User's Disk Usage
  • du -sh /home/john

Shortcuts Commands

Bash Comman Shortcuts:

CommandDescription
Ctrl + AMove to the beginning of the line
Ctrl + EMove to the end of the line
Ctrl + UCut text from cursor to start
Ctrl + KCut text from cursor to end
Ctrl + YPaste the last cut text
Ctrl + LClear the terminal screen
Ctrl + RSearch command history
TabAutocomplete file or command
!!Repeat the last command
!nRun command number n from history

Bash Useful Commands:

CommandDescriptionExamples
aliasCreate an alias for a command
  • alias ll='ls -la'
historyShow command history
  • alias ll='ls -la'
exportSet environment variables
  • export PATH=$PATH:/opt/bin
grepSearch text using patterns
  • grep "pattern" file.txt
findSearch for files in a directory
  • find /path -name file.txt
chmodChange file permissions
  • chmod 755 script.sh
chownChange file owner and group
  • chown user:group file.txt
psDisplay currently running processes
  • ps aux
killTerminate a process by PID
  • kill -9 12345
topDisplay real-time system processes
  • top

Nano Shortcuts Commands:

CommandDescription
Ctrl + OWrite (save) the file
Ctrl + XExit Nano
Ctrl + GDisplay Help
Ctrl + KCut current line
Ctrl + UPaste the cut line
Ctrl + WSearch for a text in the file
Ctrl + CShow cursor position (line/column)
Alt + AStart marking text
Ctrl + \Find and replace text
Ctrl + _Go to a specific line

VI Shortcuts Commands:

Vi Modes
  • Insert Mode: Press i to insert text.
  • Command Mode: Press Esc to switch to command mode.
  • Visual Mode: Press v to start visual selection.
CommandDescription
iEnter insert mode
EscExit insert mode and return to command mode
:wSave the file
:qQuit
:wqSave and quit
:q!Quit without saving
ddDelete the current line
yyCopy the current line
pPaste copied content
/textSearch for 'text'
nRepeat the last search
uUndo last action
Ctrl + rRedo an undone action

Vim Shortcuts Commands:

Vim is a improved version of vi

Vim Modes
  • Normal Mode: For navigating and executing commands.
  • Insert Mode: For inserting text (i to enter).
  • Command-Line Mode: For running commands (: to enter).
  • Visual Mode: For selecting text (v to enter).
CommandDescription
iEnter insert mode
EscExit insert mode and return to command mode
:wSave the file
:qQuit
:wqSave and quit
:q!Quit without saving
ddDelete the current line
yyCopy the current line
pPaste copied content
/textSearch for 'text'
nRepeat the last search
uUndo last action
Ctrl + rRedo an undone action
ggGo to the beginning of the file
GGo to the end of the file
vEnter visual mode (to select text)