Shell脚本中的循环

Posted by Xuan on February 18, 2020

Shell中简单for循环的几种形式

1.变量 ${sample}

for sample in name1 name2 name3
do
	${sample}.input > result_${sample}.output
done

2.遍历数值数组 array=(15 16 17 18 13)

array=(1 2 3 4 5)

for i in $(seq 0 5);
do
mv  correct.fa ${array[i]}_correct.fa
done

遍历(不带数组下标):

for element in ${array[@]}
#也可以写成for element in ${array[*]}
do
echo $element
done

遍历(带数组下标):

for i in "${!arr[@]}";   
do   
    printf "%s\t%s\n" "$i" "${arr[$i]}"  
done  

3.遍历当前路径下,某类指定文件 *.txt

for file in $(find . -type f -name "*.txt" -print); do
    echo $file
done

4.从shell脚本往python里传参

注意引号

a="--corrected_file=bcool_chr1_2in.txt";
b="--truth_file=groundtruth_${id[i]}_4in.txt";
python /data/xuanzhan/err_correct/code/evaluate_cor.py $a $b >> Results_bcool.txt;

shell中的数组

  • 数组定义 :array_name=(value1 value2 … valuen)

  • 数组元素 :${array_name[index]}

  • 获取数组中的所有元素(@/):${my_array[]} ${my_array[@]}
  • 获取数组的长度 : ${#my_array[@]}

Tricks

  • 连续多行变为一行

    paste - - - (连续三行变为一行)

  • awk 传入参数

    awk -v value=${sample}

  • shell传参

    Shell中的getopt传参