for Loop
ii=(1 4 15 16 32 40 41 58 61 72 73 74 97); for i in ${ii[@]}; do echo $i; done for i in {1..12}; do echo $i; done for i in {1..12..2}; do echo $i; done for i in `seq 0 12`; do echo $i; done
- break, continue
- The break command terminates the loop (breaks out of it), while continue causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle.
case
case word in pattern1) list of command ;; pattern2) list of command ;; esac
while
while [ -e $trash_dir/$newfile ]; do random_suffix=$RANDOM newfile=${file}.${random_suffix} done
until
opposite to while, it does something repeatedly until the condition is ture.
If conditional
if COMMANDS ; then COMMANDS; [ elif COMMANDS; then COMMANDS ; ]... [ else COMMANDS; ] fi
http://www.thegeekstuff.com/2010/06/bash-conditional-expression/
In the above web page, example 6 explains the difference between [ and [[ (single square bracket and double square bracket). The [[ is an enhanced version of [, normally we do NOT need to use [[ unless we want to use globbing feature and etc. In contrast to [ which is a command like "test", [[ is a keyword, and [[ is only recognized in korn and bash.
http://steve-parker.org/sh/test.shtml
-e exist file -d directory exist -eq equal number -ne not equal -gt a greater than b -lt less than -nt newer than -ot older than == same string != not same string -z true if string size is zero =~ regular expression
ps: == only works in bash, run 'bash script.sh' instead of 'sh script.sh'.
if [ -e chrX.idx ]; then echo "index file exist!"; else nohup ./segemehl.x -d chrX.fa -x chrX.idx fi
if [ ! -d $outdir ]; then mkdir $outdir; fi
for directory:
if [ -d ./doc/ ]; then
Nested If conditionals
if condition then if condition then ..... .. do this else .... .. do this fi else ... ..... do this fi
if [ condition ] then action elif [ condition2 ] then action2 . . . elif [ condition3 ] then else actionx fi
Condition and string comparison
S1='name' S2='Name' if [ $S1 == $S2 ]; # NOTE [with spaces] then echo "$S1 == $S2"; else echo "$S1 != $S2 "; fi if [ -e ./tmp.sh ]; then echo "file exist\n"; else echo "no file\n"; fi
Array
mm="2 4"; dd="random normal X1 link"; for m in $mm; do for d in $dd; do echo $m.$d; done; done;
or
mm=(2 4); dd=(random normal X1 link); for m in "${mm[@]}"; do for d in "${dd[@]}"; do echo $m.$d; done; done;
-
convert string to array
str='1 2 3 a b c' array=($str)
-
push array
array=() for i in `seq 1 8`; do array=(${array[@]} $i) done reference: [http://www.thegeekstuff.com/2010/06/bash-array-tutorial/ The Ultimate Bash Array Tutorial with 15 Examples]
Hide Comments