Skip to content

Instantly share code, notes, and snippets.

@MaxPleaner
Last active August 29, 2015 14:24
Show Gist options
  • Save MaxPleaner/1f91f703601fe795a1a9 to your computer and use it in GitHub Desktop.
Save MaxPleaner/1f91f703601fe795a1a9 to your computer and use it in GitHub Desktop.
Notes from http://www.learnshell.org/
---------------------------------------------
Interpreter name -
ps | grep $$
(assumed to be "bash")
Interpreter path -
which bash
Shim -
#!/bin/bash
Variables -
$VAR_NAME
#{VAR_NAME}
Capture command output -
`echo 'command'`
#(echo 'command')
Arrays -
arr=(item item2 "item3")
arr[6]="asd"
${arr[6]} # => "asd"
${#arr[@]} # => array length
${arr[${$arr[@]}]-1} # => last item
Operators -
$((expression))
add, substract, multiply, divide, modulo, exponent
+ - * / % **
Numeric Comparison
Expression | Condition
-------------------------------------
$a -lt $b $a < $b
$a -gt $b $a > $b
$a -le $b $a <= $b
$a -ge $b $a >= $b
$a -eq $b $a is equal to $b
$a -ne $b $a is not equal to $b
Strings -
STR="strr"
${#STR} # => length
#{STR:2} # => substring for 2..-1 range
${STR:0:2} # => 2-char substring from 0 index
expr index "asd" "sd" # => first index of substring
${STRING[@]// not/} # => remove substring
${STRING[@]/be/eat} # => find / replace first
${STRING[@]//be/eat} # => find / replace all
${STRING[@]/#to be/eat now} # => find / replace substring
${STRING[@]/%be/eat} # => find / replace substr if at end
String Comparison
Expression | Condition
-------------------------------------
"$a" = "$b" $a is the same as $b
"$a" == "$b" $a is the same as $b
"$a" != "$b" $a is different from $b
-z "$a" $a is empty
If / Else
if [ expression ]; then
echo "true"
elif [ expression2 ]; then
echo "also true"
else
echo "false"
fi
Case
case "$variable" in
"$condition1" )
command...
;;
"$condition2" )
command...
;;
esac
Loop over array
NAMES=(Joe Jenny Sara Tony)
for N in ${NAMES[@]} ; do
echo "My name is $N"
done
Loop over command results
for f in $( ls prog.sh /etc/localtime ) ; do
echo "File is: $f"
done
Other loop types
while
until
Loop keywords
"break" and "continue"
Functions
function_name {
echo "(($1 + $2))" # => arguments
}
function_name 1 2 # => call function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment