User Tools

Site Tools


shell_or_bash_scripts

This is an old revision of the document!


Shell or Bash Scripts

ShebangHeader, 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<code> vs Execute in current shell:<code>./path/to/script.sh

Guides

Executing the script

Sourcing. Eecute in a new shell - e.g. cd doesn't modify current path

. path/to/script.sh

Execute in current shell:

./path/to/script.sh
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`
shell_or_bash_scripts.1464157436.txt.gz · Last modified: (external edit)