Catalog / POSIX Shell Scripting Cheatsheet
POSIX Shell Scripting Cheatsheet
A quick reference guide to POSIX shell scripting, covering syntax, commands, and best practices for writing portable and robust shell scripts.
Basic Syntax & Structure
Script Structure
This line should be the first line of the script. It tells the system which interpreter to use to execute the script. Using |
Comments are used to explain the code and are ignored by the interpreter. |
Commands are executed sequentially, one per line. Each line typically contains a single command or a control structure. |
Semicolons ( Example: |
Use A status of |
Variables
Variable Assignment |
Example: |
Variable Access |
Example: |
Read-only Variables |
Example: |
Unsetting Variables |
Example: |
Special Variables |
$0: Script name |
Input and Output
Example: |
Example: |
Example: |
Example: |
Control Structures
Conditional Statements (if/then/else/fi)
Example:
|
Conditions are often enclosed in square brackets Example: |
String comparison: |
Looping (for/while/until)
Example:
|
Example:
|
Example:
|
|
Case Statements
Example:
|
The |
Commands and Utilities
File Manipulation
|
List directory contents |
|
Create a directory |
|
Remove a file |
|
Remove an empty directory |
|
Copy a file |
|
Move or rename a file |
|
Create an empty file or update its timestamp |
Text Processing
|
Search for a pattern in a file |
|
Replace text in a file |
|
Print the first field of each line in a file |
|
Sort the lines in a file |
|
Remove duplicate lines from a file |
|
Cut out sections of each line of a file |
Process Control
|
List running processes |
|
Terminate a process |
|
Pause execution for a specified number of seconds |
command & |
Run a command in the background |
|
Wait for all background processes to complete |
Functions and Advanced Features
Functions
Example:
|
Functions can accept arguments: Example:
|
|
Local variables can be declared using Example:
|
Command Substitution
Example:
|
Here Documents
Example:
|
Signal Handling
Example:
|
Common signals: |