command line, shell

Variables and functions in bash

$PPID prints the bash’s parent process ID

$ echo $PPID
32147

Readonly variables

Use readonly prefix before assigning a variable to make it immutable.

$ readonly VAR='some message'
$ VAR='message update'
bash: VAR: readonly variable
$ echo $VAR  
'some message'

Environment variables

env command lists all the environment variables. That isn’t all the variables that are set in you shell, though. They are only environment variables that are exported to precesses that you start in the shell. If you want to see all the variables that are available in current shell session, use the command below. compgen is a command that generates list of possible ‘word completions’ in bash when you hit tab repeatedly.

$ env
SHELL=/bin/zsh
LSCOLORS=Gxfxcxdxbxegedabagacad
ITERM_PROFILE=Default
COLORTERM=truecolor
LESS=-R
[...]
$ compgen -v
BASH
BASHOPTS
BASHPID
BASH_ALIASES
BASH_ARGC
BASH_ARGV
BASH_ARGV0
[...]

Exporting variables

We can assign variable in a ‘normal’ way or we can export a variable. The difference is, that when variable is exported, in can be use in subsequent process called in the bash, eg some scripts.

$ VAR1='var1'
$ export VAR2='var2'

---  script.sh
#!/bin/bash

echo 'VAR1: ' $VAR1
echo 'VAR2: ' $VAR2
---

$ ./script.sh
VAR1:
VAR2:  var2

Variable scopes

Variables can have scope in bash. This is particularly useful in functions, where you don’t want your variables to be accessible from outside the function.

--- script.sh ---

#!/bin/bash

function print_variable {
    echo $myvar
}

print_variable
myvar='Overriden variable'
print_variable

function local_variable {
    local myvar='Local variable'
    echo $myvar
}

local_variable
echo $myvar
local myvar='Can I change it?'

---          ---

$ ./script.sh

Overriden variable
Local variable
Overriden variable
./functions.sh: line 18: local: can only be used in a function

Overriding a builtin

If you want to know what functions are set in your environment, run declare -f. This will show the functions with their bodies. If you just want the function names, use the -F flag. This feature can be useful when we want to check if some builtin functions, eg cd are not overriden and whether we can use it safely.

Builtins vs programs

To determine if given command is builtin or program, use type builtin.

$ type grep
grep is /usr/bin/grep

$ type pwd
pwd is a shell builtin