如何在Bash大括号扩展(brace expansion)中使用变量生成序列
Bash变量传入大括号扩展生成序列的解决方案
方案1:使用seq命令
seq原生支持传入变量生成序列,配合格式化参数可实现前导零补位:
start=00 end=03 echo $(seq -f "file-%02g" $start $end) # 输出结果:file-00 file-01 file-02 file-03
参数说明:-f "%02g"指定输出为2位数字,不足位数自动补前导零,无需补零可删除该参数。
方案2:纯Bash内置实现(推荐)
完全使用Bash内置功能,无需调用外部命令,无安全风险,性能更优:
start=00 end=03 # 10#前缀强制按十进制解析,避免前导零被识别为八进制数 start_int=$((10#$start)) end_int=$((10#$end)) result=() for ((i=start_int; i<=end_int; i++)); do result+=("file-$(printf "%02d" $i)") done echo "${result[@]}" # 输出结果:file-00 file-01 file-02 file-03
方案3:使用eval(不推荐)
仅当你完全可控start和end的取值(无用户输入)时可临时使用:
start=00 end=03 eval echo file-{$start..$end} # 输出结果:file-00 file-01 file-02 file-03
注意:该方案存在命令注入风险,若变量包含用户可控内容请勿使用。
内容的提问来源于stack exchange,提问作者blueFast
相关产品推荐
相关产品推荐

