๐ Shell Scripting Syntax Guide
This guide covers the essential shell scripting syntax you need to write powerful bash scripts. ๐ง โจ
๐ 1. Script Declarationโ
Start your script with the shebang line:
bash snippet
It tells the system which interpreter to use.
๐งพ 2. Commentsโ
Use # for comments:
bash snippet
๐งฎ 3. Variablesโ
bash snippet
No space around =. Access with $variable.
๐ง 4. Conditionalsโ
๐ธ If-Elseโ
bash snippet
๐ธ Test Operatorsโ
| Operator | Meaning |
|---|---|
| [[-z string]] | Empty string |
| [[-n string]] | Not empty string |
| [[string == string]] | Equal |
| [[string != string]] | Not Equal |
| [[num -eq num]] | Equal |
| [[num -ne num]] | Not equal |
| [[num -lt num]] | Less than |
| [[num -le num]] | Less than or equal |
| [[num -gt num]] | Greater than |
| [[num -ge num]] | Greater than or equal |
| [[string =~ string]] | Regexp |
| (( num < num )) | Numeric conditions |
| [[-o noclobber]] | If OPTIONNAME is enabled |
| [[! EXPR]] | Not |
| [[X || Y]] | Or |
| [[X && Y]] | And |
๐ธ File conditionsโ
| Operator | Meaning |
|---|---|
| [[-e FILE]] | Exists |
| [[-r FILE]] | Readable |
| [[-h FILE]] | Symlink |
| [[-d FILE]] | Directory |
| [[-w FILE]] | Writable |
| [[-s FILE]] | Size is > 0 bytes |
| [[-f FILE]] | File |
| [[-x FILE]] | Executable |
| [[FILE1 -nt FILE2]] | 1 is more recent than 2 |
| [[FILE1 -ot FILE2]] | 2 is more recent than 1 |
| [[FILE1 -ef FILE2]] | Same files |
๐ 5. Loopsโ
๐ธ For Loopโ
bash snippet
๐ธ While Loopโ
bash snippet
๐ธ Until Loopโ
bash snippet
๐ค 6. Functionsโ
bash snippet
๐ฆ 7. Arraysโ
bash snippet
๐ 8. File Input/Outputโ
bash snippet
๐ฅ 9. Exit Statusโ
bash snippet
0 = success, non-zero = failure
๐ 10. Case Statementโ
bash snippet
๐ซ 11. Error Handlingโ
bash snippet
๐ 12. Read User Inputโ
bash snippet
๐ 13. Quotesโ
" ": allow variable expansion' ': literal string`or$(...): command substitution
bash snippet
๐ 14. Useful Shortcutsโ
| Shortcut | Description |
|---|---|
&& | Run next if previous success |
|| | Run next if previous fails |
$(...) | Command substitution |
${var} | Variable expansion |
"$@" | All script args |
๐ฏ 15. Script Argumentsโ
bash snippet
โ Thatโs a wrap! You now have a handy reference to shell scripting syntax!