You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bash脚本中获取不定数量命令行参数并修复数组输出问题?

修复bash数组输出只显示第一个元素的问题

你的问题出在数组的输出语法上:在bash中,直接使用${targetFiles}只会返回数组的第一个元素,要输出数组的所有元素,需要使用正确的数组展开语法。

具体修复步骤

将输出数组的代码行:

echo "Target files: ${targetFiles}"

修改为:

echo "Target files: ${targetFiles[@]}"

语法说明

  • ${array[@]}:会展开数组的所有元素,每个元素作为独立的字符串(如果文件名包含空格,也能正确保留每个文件名的完整性)。
  • ${array[*]}:会用当前系统的IFS分隔符(默认是空格)将所有数组元素连接成一个字符串输出,适合文件名不含空格的场景。

修复后的完整脚本

#!/bin/bash

if [[ $# -eq 0 || $# -eq 1 ]]; then
    echo "Usage: $0 <source file> <target 1> <target 2> ... <target n>"
    exit 1
fi

numFiles=$(($# - 1))
echo "${numFiles} target files"

sourceFile="$1"
echo "Source file: ${sourceFile}"

targetFiles=(${@: 2})
echo "Target files: ${targetFiles[@]}"

验证效果

执行命令splitFile.sh source.txt t1.txt t2.txt t3.txt后,将得到预期输出:

3 target files
Source file: source.txt
Target files: t1.txt t2.txt t3.txt

内容的提问来源于stack exchange,提问作者Vihung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:35:56