What you must know before you start bash scripting

If you have any questions about the content on this page, don't hesitate to open a new ticket and we'll do our best to assist you.

Gotchas

By understanding the following few gotchas, you can save yourself some hair pulling and hours of frustration. There are a few things that you must be aware of, as your read documentation, tutorials and code examples.

Spaces are significant: Beware of the existence or absence of an extra space before and after such characters as =, ;, [, ], {, }. The space is significant. Not respecting its use will break code snippets you may be learning from.

# Wrong variable declarationmyvar = "Hello"# Right:myvar="Hello"

New lines: some code may be written in a single line or on several lines. However, be aware that the 'punctuation' may need to be adjusted.

function echo_cat { echo "Cat!"}# Note the extra ";" before the closing bracket. It is not necessary in the function above.function echo_dog { echo "Dog!"; }

Double punctuation: in some places (e.g. switch-case statements) , we do need two semi-colon: ;;.

Use quotes: although variables may be used unquoted, you will save yourself some headaches if you always use quotes. The value of a parameter may contain spaces!

# Brittle:cat $1# Somewhat safer:cat "$1"

Documentation

The official GNU Bash documentation is not at all suitable for beginners. It is a terse technical specification document, not a tutorial for beginners.
However, the Linux Documentation Project (TLDP) is hosting very accessible Bash scripting tutorials. You may start there!

Not only bash has its own man page, but many bash commands have their own, too. For example, try: man echo.