Home

Awesome

progrium/bashstyle

Bash is the JavaScript of systems programming. Although in some cases it's better to use a systems language like C or Go, Bash is an ideal systems language for smaller POSIX-oriented or command line tasks. Here's three quick reasons why:

This document is how I write Bash and how I'd like collaborators to write Bash with me in my open source projects. It's based on a lot of experience and time collecting best practices. Most of them come from these two articles, but here integrated, slightly modified, and focusing on the most bang for buck items. Plus some new stuff!

Keep in mind this is not for general shell scripting, these are rules specifically for Bash and can take advantage of assumptions around Bash as the interpreter.

Big Rules

If you know what you're doing, you can bend or break some of these rules, but generally they will be right and be extremely helpful.

Best Practices and Tips

Good References and Help

Examples

Regular function with named arguments

Defining functions with arguments

regular_func() {
	declare arg1="$1" arg2="$2" arg3="$3"

	# ...
}

Variadic functions

Defining functions with a final variadic argument

variadic_func() {
	local arg1="$1"; shift
	local arg2="$1"; shift
	local rest="$@"

	# ...
}

Conditionals: Testing for exit code vs output

# Test for exit code (-q mutes output)
if grep -q 'foo' somefile; then
  ...
fi

# Test for output (-m1 limits to one result)
if [[ "$(grep -m1 'foo' somefile)" ]]; then
  ...
fi

More todo