Golden Codes - armanexplorer planet

Practical code snippets for Django, Python, Bash, Git and All!

View on GitHub

Example:

#!/bin/bash

set -E

trap 'echo "An error occurred!"' ERR

some_function() {
  echo "Inside the function"
  some_command_that_fails
}

some_command_that_fails
set +o pipefail # disable pipefail (default)
echo 'hello' | grep 'world' | echo 'Hello World!' # prints `Hello World!`
echo $? # and this will be 0

set -o pipefail # enable pipefail
echo 'hello' | grep 'world' | echo 'Hello World!' # prints `Hello World!` again!
echo $? # but this will be 1

change positional params

set -- postgres "$@"

This command patches postgres argument as the first positional argument along the existing ones ($@)

set --: This part is specific to the shell scripting language (like Bash). It clears any existing positional parameters (arguments passed to the script) and sets the following arguments as new positional parameters.

postgres: This is likely the actual command to be executed, which is probably the psql client for interacting with PostgreSQL.

"$@": This expands to all the arguments that were originally passed to the script itself.