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]}
donefoo="asdf"
echo${#foo} # 4 - lenght of fooi=0
((i++)) # i=1
((i+=3)) # i=4$(cmd) # POSIX
`cmd` # more or less obsolete for Bash
$((cmd)) # arithmetic expansion
$( (cmd) ) # explicit subshell (cmd) inside the command substitution $( )echo `echo `ls`` # INCORRECT
echo `echo \`ls\`` # CORRECT
echo $(echo $(ls)) # CORRECT
echo "$(echo "$(ls)")" # nested double-quotesgit commit && git push
git commit || echo "Commit failed"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
name="Johnny"
# ${FOO:0:2} Substring (position, length)
echo ${name:0:2} #=> "Jo"
echo ${name:0:-2} #=> "John" # ${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 setThis is bash, where you can use (( )) and >:
if (( a > b )); then
...
fiThis is POSIX shell, where you use [ ] and cannot use >, but -gt:
if [ "$a" -gt "$b" ]; then
...
fiwhile true; do
read -p "Do you wish to install this program?" yn
case $yn in
[Yy]* ) make install; break;; # also Y|y or Y|y|Yes|yes
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
doneCTRL + Z
It pause running command and put it to background. With jobs you can see cmd in backgrounds. To resume cmd in background type bg or to foreground with fg. If you have more than one jobs you can use bg %N or fg %N.
shuf -n N input > output