【问题标题】:Checking cmd line argument in bash script bypass the source statement检查 bash 脚本中的命令行参数绕过源语句
【发布时间】:2013-09-14 07:12:00
【问题描述】:

我有一个这样的 bash 脚本“build.sh”:

# load Xilinx environment settings
source $XILINX/../settings32.sh

cp -r "../../../EDK/platform" "hw_platform"

if [ $# -ne 0 ]; then
    cp $1/system.xml hw_platform/system.xml
fi

echo "Done"

通常我将它作为“./build.sh”运行并执行“源”语句以正确设置环境变量。有时我需要让脚本从其他地方复制文件,我将其运行为“./build.sh ~/alternative_path/”;我的脚本通过检查 $# 与 0 来检查是否有 cmd 行参数。

当我这样做时,脚本开头的“源”语句不知何故被跳过,构建失败。我在“source”前后放置了两个“echo”,我看到 echo 语句被执行了。

目前我通过“source $XILINX/../settings32.sh; build.sh”规避了这个问题。但是,请告知我在脚本中做错了什么?谢谢。

【问题讨论】:

  • 你怎么知道源语句被跳过了?
  • 我不相信你。在settings32.sh 中添加一个回显语句,我敢打赌它会执行。我的猜测是 settings32.sh 正在检查 $# 而不是设置您需要的变量。
  • set -x 放在source 行之前,这将显示所有执行的命令。这可以帮助您了解哪里出了问题。

标签: linux bash shell command-line-arguments


【解决方案1】:

尝试先将位置参数的值存储在数组变量中,然后将它们重置为 0。"$XILINX/../settings32.sh" 在检测到某些参数时可能会有所不同。

# Store arguments.
ARGS=("$@")

# Reset to 0 arguments.
set --

# load Xilinx environment settings
source "$XILINX/../settings32.sh"

cp -r "../../../EDK/platform" "hw_platform"

if [[ ${#ARGS[@]} -ne 0 ]]; then
    cp "${ARGS[0]}/system.xml" hw_platform/system.xml
fi

echo "Done"

【讨论】:

  • 感谢成功,实际上是因为setting32.sh中的代码导致了问题!
猜你喜欢
  • 1970-01-01
  • 2015-05-05
  • 2017-12-29
  • 2018-03-10
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 2021-12-31
  • 2015-07-29
相关资源
最近更新 更多