Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Arrays
- ```bash
- distro=("redhat" "debian" "gentoo")
- echo ${distro[0]}
- echo ${distro[2]} # will print gentoo
- echo ${#distro[@]} # print array size, here 3
- tLen=${#distro[@]}
- for (( i=0; i<${tLen}; i++ ));
- do
- echo ${distro[$i]}
- done
- ```
- ## Basic
- ```bash
- foo="asdf"
- echo${#foo} # 4 - lenght of foo
- ```
- ### Incrementation
- ```bash
- i=0
- ((i++)) # i=1
- ((i+=3)) # i=4
- ```
- ### Command substitution
- ```bash
- $(cmd) # POSIX
- `cmd` # more or less obsolete for Bash
- $((cmd)) # arithmetic expansion
- $( (cmd) ) # explicit subshell (cmd) inside the command substitution $( )
- ```
- #### Nesting
- ```bash
- echo `echo `ls`` # INCORRECT
- echo `echo \`ls\`` # CORRECT
- echo $(echo $(ls)) # CORRECT
- echo "$(echo "$(ls)")" # nested double-quotes
- ```
- ### Condition execution
- ```bash
- git commit && git push
- git commit || echo "Commit failed"
- ```
- ## Parameter expansions
- ### Substitution
- ```bash
- STR="/path/to/foo.cpp"
- # ${FOO%suffix} Remove first suffix
- echo ${STR%.cpp} # /path/to/foo
- echo ${STR%.cpp}.o # /path/to/foo.o
- # ${FOO%%suffix} Remove long suffix
- # ${FOO#prefix} Remove prefix
- echo ${STR#*/} # path/to/foo.cpp
- # ${FOO##prefix} Remove long prefix
- echo ${STR##*.} # cpp (extension)
- echo ${STR##*/} # foo.cpp (basepath)
- # ${FOO/from/to} Replace first match
- echo ${STR/foo/bar} # /path/to/bar.cpp
- name="Johnny"
- echo ${name/n/N} #=> "JohNny"
- # ${FOO//from/to} Replace all
- echo ${name/n/N} #=> "JohNNy"
- # ${FOO/%from/to} Replace suffix
- BASE=${STR##*/} #=> "foo.cpp" (basepath)
- DIR=${SRC%$BASE} #=> "/path/to" (dirpath)
- # ${FOO/#from/to} Replace prefix
- ```
- ### Substrings
- ```bash
- name="Johnny"
- # ${FOO:0:2} Substring (position, length)
- echo ${name:0:2} #=> "Jo"
- echo ${name:0:-2} #=> "John"
- ```
- ### Default values
- ```bash
- # ${FOO:-val} return $FOO, or val if $FOO not set
- unset foo
- echo ${food:-Cake} #=> "Cake"
- echo $food #=> ""
- food="Pie"
- echo ${food:-Cake} #=> "Pie"
- # ${FOO:=val} Set $FOO to val if $FOO not set
- unset foo
- echo ${food:=Cake} #=> "Cake"
- echo $food #=> "Cake"
- food="Pie"
- echo ${food:=Cake} #=> "Pie"
- # ${FOO:+val} return val if $FOO is set
- unset foo
- echo ${food:+Cake} #=> ""
- echo $food #=> ""
- food="Pie"
- echo ${food:+Cake} #=> "Cake"
- # ${FOO:?message} Show error message and exit if $FOO is not set
Add Comment
Please, Sign In to add comment