Linux Syntax Cheat Sheet

Linux Syntax Cheat Sheet

Digital artwork depicting Linux Syntax Cheat Sheet focusing on core Linux syntax and commands

Navigating the filesystems of Linux and shell scripting syntax can be overwhelming, we get it. When managing our customer’s dedicated servers and deploying software at IOFLOOD, having a solid grasp of Linux shell scripting is crucial for efficient administration and process automation. To aid developers and sysadmins in mastering Linux syntax and shell scripting, we’ve curated a comprehensive Linux Syntax Cheat Sheet.

This Linux Cheat Sheet includes a thorough command reference section covering file system operations, scripting techniques, and more, followed by a practical Linux code example. The command reference is complete with descriptions and syntax examples for a wide array of Linux commands and concepts while the code example provides practical demonstrations of how to put these commands to use. With this cheat sheet by your side, you’ll have a reliable map to guide you through.

Let’s embark on a journey to become Linux command line wizards together!

Command Reference Section

As we delve into the heart of Linux scripting, our first stop is the command reference section. This comprehensive guide covers the essentials, from file manipulation and system administration to advanced scripting techniques. Each entry is accompanied by a description and an example to illustrate its syntax and usage. This section should serve as a helpful list of commands and provide insight to the Linux command line.

Shell Scripting Concepts

ConceptDescriptionSyntax Example
VariablesStores data that can be used in scriptsname="John"
LoopsExecutes commands multiple timesfor i in {1..5}; do echo "Welcome $i times"; done
ConditionalsExecutes commands based on conditionsif [ "$a" -eq "$b" ]; then echo "Equal"; fi
Input/OutputManages input and output redirectionecho "Hello" > file.txt
Command Line ParametersAccesses script argumentsecho $1
String ManipulationManipulates strings${str:0:5}
Array HandlingManages collections of elementsarr=(one two three); echo ${arr[2]}
Environment VariablesSets or uses environment variablesexport PATH="$HOME/bin:$PATH"
Regular ExpressionsSearches or manipulates strings using patternsgrep -E '^a.*$' file.txt

Linux Text Editors

Text EditorDescriptionKey Commands / Features
viA classic text editor that comes with many Unix-like operating systems. It’s mode-based, allowing for efficient text manipulation and navigation.i for insert mode, :wq to save and quit
vimAn improved version of vi with additional features such as syntax highlighting, mouse support, and a comprehensive plugin system.yy to copy a line, p to paste
nanoAn easy-to-use text editor ideal for beginners and those preferring a simple interface.Ctrl + O to save, Ctrl + X to exit
emacsA customizable text editor with its own programming language (Emacs Lisp), enabling it to do much more than just text editing.Ctrl + x Ctrl + s to save, Ctrl + x Ctrl + c to quit
geditThe default text editor for the GNOME desktop environment, offering a clean interface and syntax highlighting for various programming languages.GUI-based with plugins and theme support
Sublime TextA sophisticated text editor for code, markup, and prose with a slick user interface and an extensive package ecosystem.Ctrl + Shift + P for the command palette
VS CodeA free, open-source editor developed by Microsoft with strong support for development operations like debugging, task running, and version control.Integrated terminal, extensive extension library

Scripting Languages for Linux

LanguageDescriptionKey Features
PythonPopular, versatile, and easy-to-learn.Wide library support, readability.
PerlPowerful text processing and system management.Regex and string manipulation.
RubyUser-friendly syntax with a focus on simplicity.Blocks and iterators, Rails framework.

Basic Usage of Git

CommandDescriptionExample Usage
cloneCopies a repository into a new directory.git clone [URL]
commitSaves changes to the local repository.git commit -m "[message]"
pushUploads local repository content to a remote.git push origin [branch]
pullFetches from and integrates with another repo.git pull origin [branch]
branchLists, creates, or deletes branches.git branch [branch-name]
mergeCombines two branches.git merge [branch-name]

System Administration

Users and Groups

CommandDescriptionSyntax Example
useraddCreates a new user accountuseradd -m username
usermodModifies a user accountusermod -aG groupname username
passwdUpdates a user’s passwordpasswd username
adduserAdds a user to the system (user-friendly wrapper around useradd)adduser newusername
deluserDeletes a user from the systemdeluser username
userdelRemoves a user account and related filesuserdel -r username
groupaddCreates a new groupgroupadd groupname
groupdelDeletes a groupgroupdel groupname
groupsDisplays the groups a user is ingroups username

Process Management

CommandDescriptionSyntax Example
systemctlControls the systemd system and service managersystemctl start servicename
serviceManages services under SysVinitservice servicename start
psDisplays information about active processesps aux
topDisplays real-time system processes in a sorted listtop
htopInteractive process viewer (enhanced top)htop
killSends a signal to terminate a processkill -9 PID
pkillTerminates processes based on name and other attributespkill processname
niceStarts a process with a given prioritynice -n 10 command
reniceChanges the priority of an already running processrenice 10 -p PID
nohupRuns a command immune to hangups, with output to a non-ttynohup command &
jobsLists jobs running in the current sessionjobs
fgBrings a job to foregroundfg %jobnumber
bgResumes a job in the backgroundbg %jobnumber

Package Management

CommandDescriptionSyntax Example
apt-get(Debian/Ubuntu) High-level package management commandapt-get install packagename
yum(Red Hat/Fedora) Package manager for RPMsyum install packagename
pacman(Arch) Package manager for Arch Linuxpacman -S packagename
dpkg(Debian/Ubuntu) Low-level package managerdpkg -i packagefile.deb
rpm(Red Hat/Fedora) RPM package managerrpm -ivh packagefile.rpm
apt(Debian/Ubuntu) Improved apt-get commandapt install packagename
zypper(openSUSE) Package managerzypper install packagename
dnf(Fedora) Next-generation package managerdnf install packagename

System Information

CommandDescriptionSyntax Example
unameDisplays system informationuname -a
lscpuDisplays CPU architecture informationlscpu
freeDisplays the amount of free and used memoryfree -h
uptimeShows how long the system has been runninguptime
dmesgDisplays kernel-related messagesdmesg
lsblkLists information about all available block deviceslsblk
journalctlQueries and displays messages from the journaljournalctl -u servicename
cat /var/log/Views log files stored in /var/logcat /var/log/syslog

Disk Usage and Management

CommandDescriptionSyntax Example
dfDisplays the amount of disk space available on file systemsdf -h
duEstimates file space usagedu -sh /home/user
partedA disk partitioning and partition resizing toolparted -l
fdiskA command-line utility to manage disk partitionsfdisk /dev/sda
lsblkLists information about all available or specified block deviceslsblk
mdadmA tool for managing software RAID devicesmdadm --create --verbose /dev/md0 --level=1 --raid-devices=2 /dev/sda /dev/sdb
mountMounts a filesystemmount /dev/sda2 /mnt
umountUnmounts a filesystemumount /mnt
mkfsCreates a filesystem on a devicemkfs.ext4 /dev/sda1
fsckChecks and repairs a Linux filesystemfsck /dev/sda1
blkidLocates/print block device attributesblkid /dev/sda1
resize2fsResizes ext2/ext3/ext4 file systemsresize2fs /dev/sda1
e2labelChanges the label on an ext2/ext3/ext4 filesysteme2label /dev/sda1 new-label
dumpe2fsDumps extensive filesystem informationdumpe2fs /dev/sda1

Files and Filesystem Commands

Filesystem Navigation

CommandDescriptionSyntax Example
lsLists directory contents, including files and foldersls -lah /home
cdChanges the current directorycd /var/www
pwdPrints the current working directory’s full pathnamepwd
findSearches for files in a directory hierarchyfind / -name filename.txt
locateFinds files by name quickly using a databaselocate filename.txt
whichLocates a command’s executablewhich python
duEstimates file space usagedu -sh /home/user
treeDisplays directory tree in a hierarchical structuretree /etc
grepSearches text using patternsgrep 'pattern' file.txt

File Manipulation

CommandDescriptionSyntax Example
touchCreates an empty file or updates its timestamptouch newfile.txt
cpCopies files and directoriescp source.txt destination.txt
mvMoves or renames files and directoriesmv oldname.txt newname.txt
rmRemoves files or directoriesrm file.txt
catConcatenates and displays file contentscat file.txt
morePages through text one screen at a timemore file.txt
lessSimilar to more, but allows backward movementless file.txt
headDisplays the first lines of a filehead -n 5 file.txt
tailDisplays the last lines of a filetail -n 5 file.txt
lnCreates a symbolic link to a fileln -s /path/to/file symlink
diffCompares files line by linediff file1.txt file2.txt

File Permissions

CommandDescriptionSyntax Example
chmodChanges file modes or Access Control Listschmod 755
chownChanges file owner and groupchown user:group file.txt
chgrpChanges group ownershipchgrp group file.txt
umaskSets the default permission for new filesumask 022
setfaclSets file access control listssetfacl -m u:user:r file
getfaclGets file access control listsgetfacl file

Archiving and Compression

CommandDescriptionSyntax Example
tarArchives files, optionally compressing themtar cvzf archive.tar.gz /dir
gzipCompresses files, replacing them with .gz filesgzip file.txt
gunzipDecompresses .gz filesgunzip file.txt.gz
zipPackages and compresses (archives) fileszip file1 file2
unzipExtracts and lists zip archivesunzip
bzip2Compresses files using the Burrows–Wheeler algorithmbzip2 file.txt
bunzip2Decompresses files compressed by bzip2bunzip2 file.txt.bz2
xzCompresses or decompresses .xz and .lzma filesxz file.txt
unxzDecompresses .xz filesunxz file.txt.xz

Networking and Security


Command/ConceptDescriptionSyntax Example
iptablesTool for configuring the Linux kernel’s firewalliptables -A INPUT -p tcp --dport 22 -j ACCEPT
ufwUncomplicated Firewall, a user-friendly interface for managing iptablesufw allow 22
SSH tunnellingSecurely forwards traffic from one network to anotherssh -L localPort:remoteHost:remotePort user@sshServer
Port forwardingForwards a network port from one node to anotheriptables -t nat -A PREROUTING -p tcp --dport localPort -j DNAT --to-destination remoteIP:remotePort
nmapNetwork exploration tool and security / port scannernmap -v -A
netcat (nc)Networking utility for reading from and writing to network connectionsnc -l 1234
tcpdumpCommand-line packet analyzertcpdump -i eth0
firewalldDynamic firewall manager with support for network/firewall zonesfirewall-cmd --state

Network Utilities

CommandDescriptionSyntax Example
pingSends ICMP ECHO_REQUESTS to network hostsping
netstatDisplays network connections, routing tablesnetstat -tuln
ifconfigConfigures or displays network interface parametersifconfig eth0
sshSecure Shell, a secure protocol to connect to remote serversssh user@host
scpSecure copy, copies files between hosts on a networkscp file.txt user@host:/path
wgetRetrieves content from web serverswget
curlTransfers data from or to a servercurl
tracerouteTraces the route packets take to a network hosttraceroute
ipShow / manipulate routing, devices, policy routing and tunnelsip addr
ssUtility to investigate socketsss -tulwn
ifupBrings a network interface upifup eth0
ifdownBrings a network interface downifdown eth0


Concept/ToolDescriptionSyntax Example
File permissionsControls who can read, write, or execute fileschmod 755
SSH keysPublic and private key pairs for SSH authenticationssh-keygen -t rsa
SELinuxSecurity-Enhanced Linux, a security module for access controlgetenforce
FirewallDFirewall management tool with support for network zonesfirewall-cmd --list-all-zones
Fail2banIntrusion prevention software framework that protects servers from brute-force attacksfail2ban-client status sshd
GnuPGGNU Privacy Guard, a tool for secure communication and data storagegpg --gen-key
opensslToolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocolsopenssl genrsa -out private.key 2048
chrootChanges the root directory for the current running processchroot /newroot /bin/bash
AppArmorMandatory Access Control (MAC) system, similar to SELinuxaa-status
AuditdLinux Auditing System, a framework for auditing system callsauditctl -l
Secure shell usagePractices for securing SSH, such as disabling root loginecho "PermitRootLogin no" >> /etc/ssh/sshd_config
UFWUncomplicated Firewall, easy to use interface for iptablesufw deny from

Automation & Virtualization

Automation and Orchestration

ConceptDescriptionKey Tools / Commands
ScriptingAutomating tasks through scriptsBash, Python scripts
Cron jobsSchedules tasks to run at fixed times or intervalscrontab -e to edit crontab
At jobsSchedules tasks to run once at a specific timeat 2pm + 2 days to schedule tasks
AnsibleAutomates software provisioning, configuration management, and application deploymentPlaybooks, roles
PuppetConfiguration management tool for managing multiple serversManifests, modules
KubernetesAutomates deployment, scaling, and operations of application containers across clustersPods, deployments, services

Virtualization and Containers

TechnologyDescriptionKey Commands / ToolsExample Usage
VirtualBoxA free and open-source hosted hypervisor for x86 virtualization.VBoxManageVBoxManage startvm "VM Name"
KVMKernel-based Virtual Machine provides a virtualization infrastructure for the Linux kernel.virsh, virt-managervirsh list --all
DockerA platform for developing, shipping, and running applications in isolated environments called containers.dockerdocker run hello-world
KubernetesAn open-source system for automating deployment, scaling, and management of containerized applications.kubectlkubectl get pods
LXCLinux Containers is an operating-system-level virtualization method for running multiple isolated Linux systems on a control host using a single Linux kernel.lxclxc-create -n myContainer -t download
PodmanA daemonless container engine for developing, managing, and running OCI Containers on your Linux System.podmanpodman run --name mynginx -d nginx
VagrantA tool for building and managing virtual machine environments in a single workflow.vagrantvagrant up
Docker ComposeA tool for defining and running multi-container Docker applications.docker-composedocker-compose up

Job Control

CommandDescriptionKey Features
jobsLists active jobs-l option shows process IDs
fgBrings a job to the foregroundfg %jobnumber to specify job
bgMoves a job to the backgroundbg %jobnumber to continue in background
nohupRuns a command immune to hangupsnohup command & to run in background
disownRemoves a job from the shell’s job tabledisown %jobnumber to remove job

Sample Script & Syntax

In the spirit of hands-on learning, we introduce a section dedicated to sample scripts and syntax. Here, you’ll see practical code examples that bring the previously discussed commands and concepts to life. But before we dive into the scripts, we’ll guide you through setting up your environment, so that you can run these examples on your machine.

Preparing Your Environment

  1. System Update and Package Installation: Ensure your system is updated and that all necessary packages are installed. Depending on your distribution, use either apt-get (for Debian-based systems) or yum (for Red Hat-based systems).
# Using apt-get
sudo apt-get update
sudo apt-get install -y curl vim tree openssh-client openssh-server git nano mtr iptables ufw
# Using yum
sudo yum update
sudo yum install -y curl vim tree openssh-clients openssh-server git nano mtr iptables-services firewalld
  1. User Setup: Ensure you have root privileges for executing commands that require them. If not, prepend sudo to commands as necessary.

  2. Directory and Repository Setup: Create and set up the working directory, initialize a Git repository, and prepare log files.

# Create a directory and navigate into it
mkdir -p ~/script_demo/logs && cd ~/script_demo

# Initialize a new Git repository
git init
echo "Git repository initialized."

# Prepare Logs
touch logs/network_log.txt logs/process_log.txt logs/disk_log.txt logs/user_info.txt logs/system_info.txt

# Make any desired initial edits to logs files (to be done manually with nano or another text editor)
# nano logs/[desired_log_file].txt

# Stage and commit logs to the repository
git add logs/*.txt
git commit -m "Initial commit with logs"
echo "Logs committed to the repository."
  1. Final Notes Before Running the Script:
    • Be cautious with commands that involve disk partitioning (parted, mkfs), network interface changes (ip addr add), or firewall settings (iptables, ufw). Incorrect usage may lead to connectivity issues or data loss.
    • Secondary SSD assumption: The script assumes an SSD recognized as /dev/sdb. Double-check your device labels (using lsblk or similar commands) to avoid data loss.
    • Script execution: Save the script as or another preferred name. Make it executable with chmod +x, and execute it with ./ If root privileges are required, run it with sudo ./

Sample Script

Now that you are able to run scripts on your own, we will present our sample Linux script. It is carefully made to demonstrate practical usage of the Linux commands and concepts outlined in the reference section. Through this example, you’ll learn effective scripting practices and how to combine various commands for optimal results.


# Grab information about the current user and add it to a log
echo "Current user info:" > logs/user_info.txt
whoami >> logs/user_info.txt
echo "User info logged." # Expected action: User information written to log

# Add a test user and set a temporary password
echo "Adding test user..."
sudo useradd testuser
echo testuser:Temp1234 | sudo chpasswd
echo "Test user added and password set to a simple temporary one."
echo -e "\nTest User: testuser" >> logs/user_info.txt # Append test user info to logs/user_info.txt

# Create a new group named 'samplegroup'
sudo groupadd samplegroup

# Add the current user and 'testuser' to 'samplegroup'
sudo usermod -aG samplegroup $USER
sudo usermod -aG samplegroup testuser
echo "Users added to 'samplegroup'."

# Copy a local file to a remote host
scp /path/to/local/file.txt user@remotehost:/path/to/remote/directory/
echo "File has been copied to the remote host."

# Retrieve a file from a remote host to the local machine
scp user@remotehost:/path/to/remote/file.txt /path/to/local/directory/
echo "File has been retrieved from the remote host."

# Create a private file and set permissions
echo "Creating a private file..."
touch sensitive_data.txt
chmod 600 sensitive_data.txt
echo "Sensitive data protection set." # Expected action: File permissions set to owner only

# Downloading, unpacking, and "installing" a package
echo "Downloading and installing a package..."
wget -qO example.tar.gz
tar -xzf example.tar.gz
echo "Package installed." # Expected output: Download and unpack messages

# Write system Date, Hostname, and Uptime to log
echo "Date: $(date)" > logs/system_info.txt
echo "Hostname: $(hostname)" >> logs/system_info.txt
echo "Uptime: $(uptime -p)" >> logs/system_info.txt

# Capture the most recent system logs
echo "Capturing recent system logs..."
sudo journalctl -n 10 > tmp_logs.txt # Copy recent 10 lines to a temporary log
echo -e "\nRecent System Logs:" >> logs/system_info.txt
cat tmp_logs.txt >> logs/system_info.txt # Transfer info from temporary log to main log
rm tmp_logs.txt # Remove temporary log file
echo "Recent system logs appended to logs/system_info.txt"

# Snapshot of top performance-heavy processes
echo "Grabbing top processes snapshot..."
top -b -n 1 | head -15 > logs/process_log.txt
echo "Top processes snapshot saved to logs/process_log.txt" # Expected action: Top processes info saved

# Multi-step command using awk, grep, sed
echo "Demonstrating awk/grep/sed usage..."
ps aux | grep 'bash' | awk '{print $2}' | sed 's/^/PID: /' > logs/process_log.txt
echo "Bash process PIDs logged." # Expected action: Bash process IDs logged with modification

# Job control example
echo "Starting a background job..."
sleep 60 &  # Starts a sleep command in the background
job_id=$! # Captures the Process ID of the last Job
echo "Background job started with ID: $job_id" # Expected output: Background job ID
kill $job_id # Kill the service
echo "Service (PID: $job_id) has been terminated."

# Start a long-running process (sleep for 100 seconds) in the background with nohup
nohup sleep 100 &> /dev/null &
echo "Long-running process started in the background with nohup."

# Assuming you have background jobs running, list them
fg %1 # This command will bring job 1 to the foreground, making it interactively controlled.

# Check the status of the SSH service
echo "Checking SSH service status..."
sudo systemctl status ssh | grep "Active:" > logs/system_info.txt
echo "SSH service status written to logs/service_status.txt" #

# Generate an RSA SSH key pair with a comment
ssh-keygen -t rsa -b 4096 -C "[email protected]" -f ~/.ssh/id_rsa -N ""
#Note: (-N "") leaves the passphrase empty for the key, however for security reasons, it's recommended to not use this flag, so that a passphrase can be set.
# Output the public key to the console for easy copying
cat ~/.ssh/

# Network restart and log (actual command commented out for safety)
echo "Restarting network interface (simulation)..." >> logs/network_log.txt
# sudo ifdown eth0 && sudo ifup eth0
echo "Network interface restarted." # Expected output: Network restart simulation message

# Check network connection status
echo "Checking network connection status..."
ping -c 4 > /dev/null && echo "Network is up." || echo "Network is down."
# Expected output: "Network is up." or "Network is down."

# Ping a website to check connectivity
ping -c 4

# Run mtr to trace the route to and show the results
mtr -r -c 1
# Output:
# HOST: your_local_machine              Loss%   Snt   Last   Avg  Best  Wrst StDev
#   1.|--                    0.0%     1    1.2   1.2   1.2   1.2   0.0
#   2.|--                       0.0%     1    2.4   2.4   2.4   2.4   0.0
#   3.|--                    0.0%     1   10.5  10.5  10.5  10.5   0.0

# Assign a secondary IP address to the secondary network interface (eth1)
sudo ip addr add dev eth1
sudo ip link set eth1 up # Bring the interface up
ip addr show eth1 # Check the current IP address
echo "Secondary IP configured and interface brought up."

# List current firewall Rules w/ UFW
echo "Current UFW firewall rules:"
sudo ufw status verbose
# Expected output: Lists all active rules

# Allowing incoming SSH traffic on port 22 w/ UFW
sudo ufw allow 22
echo "Incoming SSH traffic allowed."
# Expected output: Confirmation of rule addition

# Enabling IPtables service to start on boot and saving rules
# For systems using systemd
sudo systemctl enable iptables
sudo iptables-save > /etc/iptables/rules.v4
echo "IPtables service enabled on boot and rules saved."
# Expected output: Confirmation messages

# Blocking incoming traffic from a specific IP address w/ IPtables
sudo iptables -A INPUT -s -j DROP
echo "Incoming traffic from blocked."
# After configuring, don't forget to save:
sudo iptables-save > /etc/iptables/rules.v4
# Expected output: Confirmation of IP block

# Identify a new SSD (assuming /dev/sdb) and create a new partition table
echo "Creating a new GPT partition table on /dev/sdb..."
sudo parted /dev/sdb --script mklabel gpt
echo "Partition table created."

# Optionally, create a single partition covering the entire drive
sudo parted /dev/sdb --script mkpart primary ext4 1MiB 100%
echo "New partition created on /dev/sdb."
# Expected output: Confirmation of partition table and partition creation

# Create mount point and mount the SSD partition
sudo mkdir -p /mnt/ssd
sudo mount /dev/sdb1 /mnt/ssd

# Use rsync to copy logs directory to the SSD
rsync -av ~/script_demo/logs /mnt/ssd/
echo "Logs directory backed up to SSD."

# Use disk management commands to log SSD space info
echo "Logging SSD space information for /dev/sda and /dev/sdb..."
df -h | grep -E '/dev/sda|/dev/sdb' > logs/disk_log.txt
echo "SSD space information for both drives logged."

# List all block devices in a tree-like format

# List block devices with additional details like the file system type, label, UUID, and mount point

# Pushing a Commit to Update the Logs
# Assuming logs are updated, add them to the staging area
git add logs/*.txt
echo "Logs added to staging area."

# Commit the update to the repository
git commit -m "Updated Logs"
echo "Log updates committed."

# Push the commit to the remote repository (assuming a remote named 'origin' is set up)
git push origin master
echo "Changes pushed to remote repository."

# (Virtualization) For Docker, a Dockerfile would include steps like:
# FROM ubuntu:latest
# COPY . /app
# RUN apt-get update && apt-get install -y cron
# CMD ["cron", "-f"]

# Schedule this script to run daily using cron (add this line to your crontab manually)
# 0 0 * * * /path/to/your/

# Final statement
echo "Script execution completed. Logs and other outputs have been generated."

From system administration to network management, this script has covered essential Linux topics and demonstrated the structure and syntax of Linux scripts. As you continue to experiment and learn, remember that this cheat sheet and the concepts it covers are valuable resources at your disposal.


Our journey through the Linux Syntax Cheat Sheet comes to a close, but your adventure in Linux scripting is just beginning. Armed with our command reference and practical coding examples, you’re well-prepared to tackle the challenges and opportunities that lie ahead. As you progress, remember that mastery is gained by continuous learning and experimentation. We wish you all the best as you forge your path in the Linux world, confident in your ability to script effectively and efficiently. Happy scripting, and may you find success in all your coding endeavors!