DEV Community

Meir Gabay
Meir Gabay

Posted on

Bash scripting tips

Naming convention

This is only a recommendation, it doesn't really set the type of the variable, rather than a best practice to easily recognize variables scope.

Type Scope Convention
Environment Global MY_VARIABLE
Global Global _MY_VARIABLE
Local Function my_variable

Environment variables

Available from anywhere in your code, including sub-processes and background-processes. Environment variables that were declared in a sub-process or a background-process are out of the scope of the main process.

sub-process

#!/bin/usr/env bash
export MAIN_VAR="MAIN_VAR value"
echo "main-process BEFORE - MAIN_VAR        = $MAIN_VAR"

# sub-process
bash -c '
export                      SUB_PROCESS_VAR="SUB_PROCESS_VAR value"
echo "sub-process         - SUB_PROCESS_VAR = $SUB_PROCESS_VAR"
echo "sub-process  BEFORE - MAIN_VAR        = $MAIN_VAR"
export                      MAIN_VAR="MAIN_VAR changed value"
echo "sub-process  AFTER  - MAIN_VAR        = $MAIN_VAR"
'

echo "main-process AFTER  - MAIN_VAR        = $MAIN_VAR"
echo "main-process        - SUB_PROCESS_VAR = $SUB_PROCESS_VAR"
Enter fullscreen mode Exit fullscreen mode

Output

main-process BEFORE - MAIN_VAR        = MAIN_VAR value
sub-process         - SUB_PROCESS_VAR = SUB_PROCESS_VAR value
sub-process  BEFORE - MAIN_VAR        = MAIN_VAR value
sub-process  AFTER  - MAIN_VAR        = MAIN_VAR changed value
main-process AFTER  - MAIN_VAR        = MAIN_VAR value
main-process        - SUB_PROCESS_VAR =
Enter fullscreen mode Exit fullscreen mode

background-process

#!/bin/usr/env bash
export MAIN_VAR="MAIN_VAR value"
echo "main-process BEFORE - MAIN_VAR       = $MAIN_VAR"

# background-process
export BG_PROCESS_VAR="BG_PROCESS_VAR value" && \
echo "bg-process          - BG_PROCESS_VAR = $BG_PROCESS_VAR" && \
echo "bg-process   BEFORE - MAIN_VAR       = $MAIN_VAR" && \
export MAIN_VAR="MAIN_VAR changed value" && \
echo "bg-process   AFTER  - MAIN_VAR       = $MAIN_VAR" \
& # set bg process

# Wait for bg processes (jobs) to complete
# Otherwise, the following lines won't be executed
wait

echo "main-process AFTER  - MAIN_VAR       = $MAIN_VAR"
echo "main-process        - BG_PROCESS_VAR = $BG_PROCESS_VAR"
Enter fullscreen mode Exit fullscreen mode

Output

main-process BEFORE - MAIN_VAR       = MAIN_VAR value
bg-process          - BG_PROCESS_VAR = BG_PROCESS_VAR value
bg-process   BEFORE - MAIN_VAR       = MAIN_VAR value
bg-process   AFTER  - MAIN_VAR       = MAIN_VAR changed value
main-process AFTER  - MAIN_VAR       = MAIN_VAR value
main-process        - BG_PROCESS_VAR =
Enter fullscreen mode Exit fullscreen mode

Top comments (0)