Bash: Array, Loop and Conditionals

From Augix' Wiki

Jump to: navigation, search

Contents

For Loop

jj=(1 4 15 16 32 40 41 58 61 72 73 74 97);
for j in `seq 0 12`; do
  qsub 3way_4tissues.anova.sge.hugemem ${jj[$j]};
done

Case

case word in
  pattern1) 
    list of command
    ;;
  pattern2)
    list of command
    ;;
esac

For 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)

reference: The Ultimate Bash Array Tutorial with 15 Examples

If conditional

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
Personal tools