Table of Contents
Shell or Bash Scripts
Shebang | Header, which tells where the interpreter is located #!/bin/sh | http://stackoverflow.com/questions/10376206/what-is-the-preferred-bash-shebang |
Sourcing | launch script in a new shell using point with an empty space between sript path Souring: . path/to/script.sh vs Execute in current shell: ./path/to/script.sh | http://superuser.com/questions/176783/what-is-the-difference-between-executing-a-bash-script-and-sourcing-a-bash-scrip |
Guides
Executing or Sourcing the script
Sourcing. Execute in the CURRENT shell
. path/to/script.sh
Executing. Execute in a NEW shell - e.g. cd doesn't modify current shell's path
./path/to/script.sh
Syntax
declare Function
Returning result is done via echo
#!/bin/bash #Define bash global variable #This variable is global and can be used anywhere in this bash script VAR="global variable" function bash { #Define bash local variable #This variable is local to bash function only local VAR="local variable" echo $VAR } echo $VAR bash # Note the bash global variable did not change # "local" is bash reserved word echo $VAR
declare Array
Small a!!!
declare -a map map[1]="myvalue" map[1]="myvalue2" echo ${map[1]}
declare Map
Big A!!!
declare -A map map[test]="myvalue" map[test2]="myvalue2" echo ${map[test2]}
iterate array keys
Access via ${!array[@]}
for i in "${!array[@]}" do echo "key : $i" echo "value: ${array[$i]}" done
dereference an array / map value
${ARRAY[2]} ${map[key1]}
If Else
- Empty spaces after the parenthesis are critical: [ $a==$b ]
# check if it is the root device if [ $device_name==$root_device_name ] then echo "$device_name is root" else echo "NOT root" fi
Command Substitution
Command substitution allows the output of a command to replace the command itself. Command substitution occurs when a command is enclosed like this:
$(command)
or like this using backticks:
`command`
Input from command line
If a command expects a file as input - one can pass input from STDOUT instead, without storing the output to a file first by using following syntax
oc create -f expects a file here.
oc process -f build/my-build-template.yaml GITSERVER=$GITSERVER | oc create -f - oc process -f build/my-build-template.yaml GITSERVER=$GITSERVER | oc create -f /dev/stdin
Double-Dash -- in Shell commands
A double-dash in a shell command signals the end of options and disables further option processing. https://www.baeldung.com/linux/double-dash-in-shell-commands
# If we use the same approach, we'll receive an error: # That's because grep treats "--hello" as a multi-character command option. grep "--hello" data.txt #works grep -- --hello data.txt