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
Concept | Description | Syntax Example |
---|
Variables | Stores data that can be used in scripts | name="John" |
Loops | Executes commands multiple times | for i in {1..5}; do echo "Welcome $i times"; done |
Conditionals | Executes commands based on conditions | if [ "$a" -eq "$b" ]; then echo "Equal"; fi |
Input/Output | Manages input and output redirection | echo "Hello" > file.txt |
Command Line Parameters | Accesses script arguments | echo $1 |
String Manipulation | Manipulates strings | ${str:0:5} |
Array Handling | Manages collections of elements | arr=(one two three) ; echo ${arr[2]} |
Environment Variables | Sets or uses environment variables | export PATH="$HOME/bin:$PATH" |
Regular Expressions | Searches or manipulates strings using patterns | grep -E '^a.*$' file.txt |
Linux Text Editors
Text Editor | Description | Key Commands / Features |
---|
vi | A 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 |
vim | An 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 |
nano | An easy-to-use text editor ideal for beginners and those preferring a simple interface. | Ctrl + O to save, Ctrl + X to exit |
emacs | A 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 |
gedit | The 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 Text | A 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 Code | A 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
Language | Description | Key Features |
---|
Python | Popular, versatile, and easy-to-learn. | Wide library support, readability. |
Perl | Powerful text processing and system management. | Regex and string manipulation. |
Ruby | User-friendly syntax with a focus on simplicity. | Blocks and iterators, Rails framework. |
Basic Usage of Git
Command | Description | Example Usage |
---|
clone | Copies a repository into a new directory. | git clone [URL] |
commit | Saves changes to the local repository. | git commit -m "[message]" |
push | Uploads local repository content to a remote. | git push origin [branch] |
pull | Fetches from and integrates with another repo. | git pull origin [branch] |
branch | Lists, creates, or deletes branches. | git branch [branch-name] |
merge | Combines two branches. | git merge [branch-name] |
System Administration
Users and Groups
Command | Description | Syntax Example |
---|
useradd | Creates a new user account | useradd -m username |
usermod | Modifies a user account | usermod -aG groupname username |
passwd | Updates a user’s password | passwd username |
adduser | Adds a user to the system (user-friendly wrapper around useradd) | adduser newusername |
deluser | Deletes a user from the system | deluser username |
userdel | Removes a user account and related files | userdel -r username |
groupadd | Creates a new group | groupadd groupname |
groupdel | Deletes a group | groupdel groupname |
groups | Displays the groups a user is in | groups username |
Process Management
Command | Description | Syntax Example |
---|
systemctl | Controls the systemd system and service manager | systemctl start servicename |
service | Manages services under SysVinit | service servicename start |
ps | Displays information about active processes | ps aux |
top | Displays real-time system processes in a sorted list | top |
htop | Interactive process viewer (enhanced top ) | htop |
kill | Sends a signal to terminate a process | kill -9 PID |
pkill | Terminates processes based on name and other attributes | pkill processname |
nice | Starts a process with a given priority | nice -n 10 command |
renice | Changes the priority of an already running process | renice 10 -p PID |
nohup | Runs a command immune to hangups, with output to a non-tty | nohup command & |
jobs | Lists jobs running in the current session | jobs |
fg | Brings a job to foreground | fg %jobnumber |
bg | Resumes a job in the background | bg %jobnumber |
Package Management
Command | Description | Syntax Example |
---|
apt-get | (Debian/Ubuntu) High-level package management command | apt-get install packagename |
yum | (Red Hat/Fedora) Package manager for RPMs | yum install packagename |
pacman | (Arch) Package manager for Arch Linux | pacman -S packagename |
dpkg | (Debian/Ubuntu) Low-level package manager | dpkg -i packagefile.deb |
rpm | (Red Hat/Fedora) RPM package manager | rpm -ivh packagefile.rpm |
apt | (Debian/Ubuntu) Improved apt-get command | apt install packagename |
zypper | (openSUSE) Package manager | zypper install packagename |
dnf | (Fedora) Next-generation package manager | dnf install packagename |
System Information
Command | Description | Syntax Example |
---|
uname | Displays system information | uname -a |
lscpu | Displays CPU architecture information | lscpu |
free | Displays the amount of free and used memory | free -h |
uptime | Shows how long the system has been running | uptime |
dmesg | Displays kernel-related messages | dmesg |
lsblk | Lists information about all available block devices | lsblk |
lsmod | Shows | |
journalctl | Queries and displays messages from the journal | journalctl -u servicename |
cat /var/log/ | Views log files stored in /var/log | cat /var/log/syslog |
Disk Usage and Management
Command | Description | Syntax Example |
---|
df | Displays the amount of disk space available on file systems | df -h |
du | Estimates file space usage | du -sh /home/user |
parted | A disk partitioning and partition resizing tool | parted -l |
fdisk | A command-line utility to manage disk partitions | fdisk /dev/sda |
lsblk | Lists information about all available or specified block devices | lsblk |
mdadm | A tool for managing software RAID devices | mdadm --create --verbose /dev/md0 --level=1 --raid-devices=2 /dev/sda /dev/sdb |
mount | Mounts a filesystem | mount /dev/sda2 /mnt |
umount | Unmounts a filesystem | umount /mnt |
mkfs | Creates a filesystem on a device | mkfs.ext4 /dev/sda1 |
fsck | Checks and repairs a Linux filesystem | fsck /dev/sda1 |
blkid | Locates/print block device attributes | blkid /dev/sda1 |
resize2fs | Resizes ext2/ext3/ext4 file systems | resize2fs /dev/sda1 |
e2label | Changes the label on an ext2/ext3/ext4 filesystem | e2label /dev/sda1 new-label |
dumpe2fs | Dumps extensive filesystem information | dumpe2fs /dev/sda1 |
Files and Filesystem Commands
Filesystem Navigation
Command | Description | Syntax Example |
---|
ls | Lists directory contents, including files and folders | ls -lah /home |
cd | Changes the current directory | cd /var/www |
pwd | Prints the current working directory’s full pathname | pwd |
find | Searches for files in a directory hierarchy | find / -name filename.txt |
locate | Finds files by name quickly using a database | locate filename.txt |
which | Locates a command’s executable | which python |
du | Estimates file space usage | du -sh /home/user |
tree | Displays directory tree in a hierarchical structure | tree /etc |
grep | Searches text using patterns | grep 'pattern' file.txt |
File Manipulation
Command | Description | Syntax Example |
---|
touch | Creates an empty file or updates its timestamp | touch newfile.txt |
cp | Copies files and directories | cp source.txt destination.txt |
mv | Moves or renames files and directories | mv oldname.txt newname.txt |
rm | Removes files or directories | rm file.txt |
cat | Concatenates and displays file contents | cat file.txt |
more | Pages through text one screen at a time | more file.txt |
less | Similar to more , but allows backward movement | less file.txt |
head | Displays the first lines of a file | head -n 5 file.txt |
tail | Displays the last lines of a file | tail -n 5 file.txt |
ln | Creates a symbolic link to a file | ln -s /path/to/file symlink |
diff | Compares files line by line | diff file1.txt file2.txt |
File Permissions
Command | Description | Syntax Example |
---|
chmod | Changes file modes or Access Control Lists | chmod 755 script.sh |
chown | Changes file owner and group | chown user:group file.txt |
chgrp | Changes group ownership | chgrp group file.txt |
umask | Sets the default permission for new files | umask 022 |
setfacl | Sets file access control lists | setfacl -m u:user:r file |
getfacl | Gets file access control lists | getfacl file |
Archiving and Compression
Command | Description | Syntax Example |
---|
tar | Archives files, optionally compressing them | tar cvzf archive.tar.gz /dir |
gzip | Compresses files, replacing them with .gz files | gzip file.txt |
gunzip | Decompresses .gz files | gunzip file.txt.gz |
zip | Packages and compresses (archives) files | zip archive.zip file1 file2 |
unzip | Extracts and lists zip archives | unzip archive.zip |
bzip2 | Compresses files using the Burrows–Wheeler algorithm | bzip2 file.txt |
bunzip2 | Decompresses files compressed by bzip2 | bunzip2 file.txt.bz2 |
xz | Compresses or decompresses .xz and .lzma files | xz file.txt |
unxz | Decompresses .xz files | unxz file.txt.xz |
Networking and Security
Networking
Command/Concept | Description | Syntax Example |
---|
iptables | Tool for configuring the Linux kernel’s firewall | iptables -A INPUT -p tcp --dport 22 -j ACCEPT |
ufw | Uncomplicated Firewall, a user-friendly interface for managing iptables | ufw allow 22 |
SSH tunnelling | Securely forwards traffic from one network to another | ssh -L localPort:remoteHost:remotePort user@sshServer |
Port forwarding | Forwards a network port from one node to another | iptables -t nat -A PREROUTING -p tcp --dport localPort -j DNAT --to-destination remoteIP:remotePort |
nmap | Network exploration tool and security / port scanner | nmap -v -A targethost.com |
netcat (nc) | Networking utility for reading from and writing to network connections | nc -l 1234 |
tcpdump | Command-line packet analyzer | tcpdump -i eth0 |
firewalld | Dynamic firewall manager with support for network/firewall zones | firewall-cmd --state |
Network Utilities
Command | Description | Syntax Example |
---|
ping | Sends ICMP ECHO_REQUESTS to network hosts | ping google.com |
netstat | Displays network connections, routing tables | netstat -tuln |
ifconfig | Configures or displays network interface parameters | ifconfig eth0 |
ssh | Secure Shell, a secure protocol to connect to remote servers | ssh user@host |
scp | Secure copy, copies files between hosts on a network | scp file.txt user@host:/path |
wget | Retrieves content from web servers | wget http://example.com |
curl | Transfers data from or to a server | curl http://example.com |
traceroute | Traces the route packets take to a network host | traceroute example.com |
ip | Show / manipulate routing, devices, policy routing and tunnels | ip addr |
ss | Utility to investigate sockets | ss -tulwn |
ifup | Brings a network interface up | ifup eth0 |
ifdown | Brings a network interface down | ifdown eth0 |
Security
Concept/Tool | Description | Syntax Example |
---|
File permissions | Controls who can read, write, or execute files | chmod 755 file.sh |
SSH keys | Public and private key pairs for SSH authentication | ssh-keygen -t rsa |
SELinux | Security-Enhanced Linux, a security module for access control | getenforce |
FirewallD | Firewall management tool with support for network zones | firewall-cmd --list-all-zones |
Fail2ban | Intrusion prevention software framework that protects servers from brute-force attacks | fail2ban-client status sshd |
GnuPG | GNU Privacy Guard, a tool for secure communication and data storage | gpg --gen-key |
openssl | Toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols | openssl genrsa -out private.key 2048 |
chroot | Changes the root directory for the current running process | chroot /newroot /bin/bash |
AppArmor | Mandatory Access Control (MAC) system, similar to SELinux | aa-status |
Auditd | Linux Auditing System, a framework for auditing system calls | auditctl -l |
Secure shell usage | Practices for securing SSH, such as disabling root login | echo "PermitRootLogin no" >> /etc/ssh/sshd_config |
UFW | Uncomplicated Firewall, easy to use interface for iptables | ufw deny from 192.168.1.1 |
Automation & Virtualization
Automation and Orchestration
Concept | Description | Key Tools / Commands |
---|
Scripting | Automating tasks through scripts | Bash, Python scripts |
Cron jobs | Schedules tasks to run at fixed times or intervals | crontab -e to edit crontab |
At jobs | Schedules tasks to run once at a specific time | at 2pm + 2 days to schedule tasks |
Ansible | Automates software provisioning, configuration management, and application deployment | Playbooks, roles |
Puppet | Configuration management tool for managing multiple servers | Manifests, modules |
Kubernetes | Automates deployment, scaling, and operations of application containers across clusters | Pods, deployments, services |
Virtualization and Containers
Technology | Description | Key Commands / Tools | Example Usage |
---|
VirtualBox | A free and open-source hosted hypervisor for x86 virtualization. | VBoxManage | VBoxManage startvm "VM Name" |
KVM | Kernel-based Virtual Machine provides a virtualization infrastructure for the Linux kernel. | virsh , virt-manager | virsh list --all |
Docker | A platform for developing, shipping, and running applications in isolated environments called containers. | docker | docker run hello-world |
Kubernetes | An open-source system for automating deployment, scaling, and management of containerized applications. | kubectl | kubectl get pods |
LXC | Linux Containers is an operating-system-level virtualization method for running multiple isolated Linux systems on a control host using a single Linux kernel. | lxc | lxc-create -n myContainer -t download |
Podman | A daemonless container engine for developing, managing, and running OCI Containers on your Linux System. | podman | podman run --name mynginx -d nginx |
Vagrant | A tool for building and managing virtual machine environments in a single workflow. | vagrant | vagrant up |
Docker Compose | A tool for defining and running multi-container Docker applications. | docker-compose | docker-compose up |
Job Control
Command | Description | Key Features |
---|
jobs | Lists active jobs | -l option shows process IDs |
fg | Brings a job to the foreground | fg %jobnumber to specify job |
bg | Moves a job to the background | bg %jobnumber to continue in background |
nohup | Runs a command immune to hangups | nohup command & to run in background |
disown | Removes a job from the shell’s job table | disown %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
- 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).
- User Setup: Ensure you have root privileges for executing commands that require them. If not, prepend sudo to commands as necessary.
Directory and Repository Setup: Create and set up the working directory, initialize a Git repository, and prepare log files.
- 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 setup.sh or another preferred name. Make it executable with chmod +x setup.sh, and execute it with ./setup.sh. If root privileges are required, run it with sudo ./setup.sh
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.
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.
Conclusion
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!