Table of Contents
- variable
- input
- conditional
- commandline arguments
- function
- array
- file check
syntax: KEY=VALUE
# General declaration
HELLO="HELLO"
HELLO2=$HELLO
NUMBER=1234
NUMBERS=(1 2 3 4)
# Numerical declaration
SOME_NUMBER=$(( $NUMBER + 2 + 3 ))
echo $SOME_NUMBER # prints 1239
A=$(( 3 * (2+1+(1+5)) ))
echo $A # prints 27
# function-scope local variable
function foo {
local LOCAL_VARIABLE=1234
}
# Check variable is set or not set
if [[ -z "$SOME_VARIABLE" ]]; then
echo "Error: variable is not set"
fi
# Unsetting variable from bash
ITEM="hello"
unset ITEM # dispose variable
# Variable as key-value store
declare -A SOME_HASHMAP # bash4 feature
SOME_HASHMAP["KEY1"]=1234
SOME_HASHMAP["KEY2"]="OH"
echo $SOME_HASHMAP # prints nothing
echo ${SOME_HASHMAP["KEY1"]} # prints 1234
bash offers builtin function read
.
read A # assign input to variable A
echo -n "Enter name: " && read A # print prompt 'Enter name: ' then assign input to variable A
read -s A # disable echoing. useful to get password
GNU coreutils has echo
and printf
utilities. If you have to format complex string, use printf
. it will work as you expected.
echo "hello" # prints "hello"
echo "$A" # prints variable A. if A is not set, it is replaced with empty string
echo -n "$A" # prints variable A without trailing newline
echo -e "\n\n$A" # enable escaping + prints variable A
if [[ $varA -eq 1 ]] && [[ $varB == 't1' || $varC == 't2' ]]; then
scale=0.05
fi
if (( $varA == 1 )) && [[ $varB == 't1' || $varC == 't2' ]]; then
fi
# decl
function foo {
echo "foo!"
echo "First ARG: $1"
}
# call
foo "some arg"
# declaration
AA=(1 2 3 4)
# getter
echo ${AA[0]}
echo ${AA[1]}
# setter
AA[4]=5
# command output to array
FILES=(`ls`) # Don't forget to wrap output with parentheses
FIRST_FILE=${FILES[0]}
# array to strings
ARR=(`ls`)
STR=${ARR[@]}
# substring
STRING="hello"
SUBSTRING=${STRING:0:2} # he
SUBSTRING=${STRING::2} # he
SUBSTRING=${STRING:1:2} # el
SUBSTRING=${STRING:2} # llo
file test operators
- -e: exists
- -f: is_file
- -s: has_size
- -d: is_directory
- -b: is_block_device
- -c: is_char_device
- -p: is_pipe
- -h: is_symbolic
- -L: is_symbolic
- -S: is_socket
- -t: is_terminal
- -r,-w,-x: can_read,can_write,can_execute
- -g: has_sgid
- -u: has_suid
- -k: has_sticky_bit
- -O: has_ownership
- -G: has_group_ownership
- -N: is_changed