Bash

This page is bash programming tips and ideas

There are various types of shells available. bash, csh, zsh.

Shebang

If we execute the script ./script.sh , it needs to have first line mentioning the interpretor. #!/bin/bash or #!/bin/csh

Users can specify all "set" options along with the shell interpretor

Execution

  • /bin/sh is the default executor. it generally points to any of the above shell. it is used by all make command executions. It is important to change the default shell

  • By default the env gets sourced. To get new shell without any user/system env. /bin/bash --norc

set options

  • Printing each line before executing. ( set -x ) to unset ( set +x)

  • By default shell execution moves further even though a particular command gets failed. To change this behaviour we need to use ( set -e )

Non Interactive Mode

There is a difference in the execution between normal shell executin and using pipe with tee command. The animating commands changes its ourput based on this mode. Ex- see the yocto bitbake command normally and check the output with pipe and tee command

set flags can be used to toggle the modes ( setops )

Interpolation

By default the variable gets substituted at the time of parsing. It will not allow to change the dependent variable.#Defining some variables

var_a="value-a"
var_b="value-b"
var_c='${var_a}/test'
# if we define var_c="${var_a}/test", it will substitue var_c="value-a/test" at the
# time of parsing
# Any further changes in var_a at later point will not get impacted on var_c
# var_c will always print "value-a/tets"

function parse_var() {
        local var=$1
        local val=$(eval "echo ${var}")
        echo ${val}
}

# Interpolate value of var_c -> var_a -> value-a
echo $var_c
parsed_var_c=$(parse_var $var_c)
echo ${parsed_var_c}

# Change the value of var_a
var_a="value-a-new"
echo $var_c
echo $(parse_var $var_c)

Pipes

Clear Broken Shell

stty sane

Useful libraries

assert functions

Coding Tips

#Usage of or in single line conditional statements
value = var1 || var2

Last updated