Shell脚本中字符串变量拼接结果顺序颠倒是什么原因?
问题原因
- 核心问题是你存放文件名的
RNA-seq_filename.txt使用了Windows格式的换行符(CRLF,即\r\n结尾),而Linux/macOS的换行符为LF(仅\n结尾)。当你用cat读取每行内容赋值给prefix时,变量末尾会被自动带上看不见的\r(回车符)。 - 回车符的作用是将光标移动到当前行的最左侧,所以你输出
${prefix}${R1}时,实际输出顺序是[prefix内容]\r[R1内容],光标移到行首后R1的内容会覆盖prefix开头的位置,视觉上就出现了字符串顺序颠倒的效果。 - 你原脚本中的长命令没有加续行符
\,跨行会被识别为多个独立命令,也是潜在的执行异常原因。
修复方案
- 第一步:先转换文件名文件的换行格式,执行以下命令即可把Windows换行转成Linux换行:
如果环境中没有dos2unix工具,也可以用sed命令实现相同效果:dos2unix /binf-isilon/PBgrp/jfb841/RNA-seq_germination/RNA-seq_filename.txtsed -i 's/\r$//' /binf-isilon/PBgrp/jfb841/RNA-seq_germination/RNA-seq_filename.txt - 第二步:优化shell脚本写法,规避空格、特殊字符等其他潜在问题,修改后的参考脚本如下:
#!/bin/bash # 固定参数提到循环外,避免重复赋值 raw_data_loc="/binf-isilon/PBgrp/jfb841/RNA-seq_germination" index_path="/binf-isilon/PBgrp/jfb841/annotations/transcriptome_index" R1="_R1_001.fastq.gz" R2="_R2_001.fastq.gz" # 用while read代替for cat读取文件,兼容性、稳定性更强 while IFS= read -r prefix || [[ -n ${prefix} ]]; do # 额外去除变量中可能存在的回车符,双重保险 prefix=${prefix//$'\r'/} echo "Processing sample ${prefix}" salmon quant -i "${index_path}" \ --libType A \ -1 "${raw_data_loc}/${prefix}${R1}" \ -2 "${raw_data_loc}/${prefix}${R2}" \ -p 48 \ -o "quants/${prefix}_quant" & done < /binf-isilon/PBgrp/jfb841/RNA-seq_germination/RNA-seq_filename.txt # 等待所有后台salmon定量任务执行完成 wait
内容的提问来源于stack exchange,提问作者Bai Bing
相关产品推荐
相关产品推荐

