Bash coding standard

From VyOS Wiki
Jump to: navigation, search

bash vs. sh

VyOS has bash installed by default and /bin/sh is a symlink to bash, so there is no reason to keep it to strict legacy Bourne shell. Everything below implies bash.

Indentation

Tabs shall not be used. Set your editor to expand tabs to spaces.

Rationale: portability.

Use four spaces per level.

function foo()
{
    if [ -f "$1" ]; then
        echo "File does not exist"
        exit 1
    fi
}

Backticks

Backticks shall not be used.

Rationale: Readability. Parentheses are easier to spot visually. Parentheses can be nested.

# Good:
    foo=$(command)

# Bad:
    foo=`command`

Conditionals

Long (if/then/else) form of conditionals should be used.

Rationale: Easier to insert additional statements or comment out the condition

# Good:
    if [ "$FOO" == "$BAR" ]; then
        do_something
    fi

# Bad:
    [ "$FOO" == "$BAR" ] && do_something

Quoting

Variables must be properly quoted.

Rationale: Empty strings cause syntax errors.

# Good:
    if [ "$FOO" == "FOOBAR" ]

# Bad:
    if [ $FOO == "FOOBAR" ]