Skip to main content

๐Ÿš 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โ€‹

OperatorMeaning
[[-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โ€‹

OperatorMeaning
[[-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โ€‹

ShortcutDescription
&&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!