Skip to content
Blog
Esc
  • Type at least two characters.
Browse Blog

Linux Cheat Sheet

Last updated by

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 neededmkdir 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 Userwhoami
dfShow disk space usage.-h: Human-readable sizes.df -h: displays disk space usage in a human-readable format.
duCheck User's Disk Usagedu -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

Display and manage networking, routing, and tunnel configurations.addr: Diplay IP Addresses. · route: Display/Manage route table. · link: Manage network interfaceip 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.
Display network interface information.-a: Display all Interfacesifconfig -a: shows the details of all network interfaces.
Send 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
Display 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.
Securely 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 Tunnelingssh 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
Securely copy files between hosts.-r: Copy Directory recursivelyscp 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.
Download files from the web.-O: Download file with defined Output Filename · -A: Download only specific file typeswget 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.
Transfer 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 Certificatescurl 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&param2=value2" http://example.com: Sends a POST request with the data param1=value1&param2=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 &lt 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 &lt&lt 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" &lt&lt&lt "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

Displays all environment variables.env
Prints specific or all environment variables.printenv PATH: Displays the value of PATH
Temporary Environment Variable (Only for current shell session)MY_VAR="HelloWorld" · export MY_VAR · echo $MY_VAR: echo will return HelloWorld
Add to .bashrc or .bash_profileecho 'export VAR_NAME="value"' >> ~/.bashrc · source ~/.bashrc
Removes an environment variable.unset MY_VAR echo $MY_VAR: echo will return emtpy output

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 usersudo useradd [OPTIONS] USERNAME · sudo useradd -m -d /home/john -s /bin/bash -c "John Doe" john
passwdSet or Update a User Passwordsudo passwd USERNAME
userdelDelete a User-r : Remove the user's home directory and mail spoolsudo 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 accountsudo 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 groupsudo groupadd GROUPNAME · sudo groupadd devops ·
suSwitch to another user- : Start a login shellsu [OPTIONS] USERNAME · su - john ·
groupsList user groupsgroups USERNAME · groups john ·
lastlogShow Last Login Informationlastlog -u john
whoamiView Current Userwhoami
duCheck User's Disk Usagedu -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 commandalias ll='ls -la'
historyShow command historyalias ll='ls -la'
exportSet environment variablesexport PATH=$PATH:/opt/bin
grepSearch text using patternsgrep "pattern" file.txt
findSearch for files in a directoryfind /path -name file.txt
chmodChange file permissionschmod 755 script.sh
chownChange file owner and groupchown user:group file.txt
psDisplay currently running processesps aux
killTerminate a process by PIDkill -9 12345
topDisplay real-time system processestop

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

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

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)