简体   繁体   English

在bash脚本中检查cmd line参数绕过source语句

[英]Checking cmd line argument in bash script bypass the source statement

I have an bash script "build.sh" like this: 我有一个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"

Normally I run it as "./build.sh" and it execute the "source" statement to set environment variables correct. 通常,我以“ ./build.sh”运行它,并执行“ source”语句以正确设置环境变量。 Sometimes I need to let the script to copy file from an alternative place, I run it as "./build.sh ~/alternative_path/"; 有时我需要让脚本从其他位置复制文件,我将其运行为“ ./build.sh〜/ alternative_path /”; My script check whether there is an cmd line argument by checking $# against 0. 我的脚本通过将$#与0进行对照来检查是否存在cmd行参数。

When I do that, the "source" statement at the beginning of the script somehow get skipped, and build failed. 当我这样做时,脚本开头的“ source”语句就会以某种方式被跳过,并且构建失败。 I have put two "echo" before and after the "source", and I see echo statements get executed. 我在“源”之前和之后放置了两个“ echo”,并且看到执行了echo语句。

Currently I circumvent this issue by "source $XILINX/../settings32.sh; build.sh". 目前,我通过“ source $ XILINX /../ settings32.sh; build.sh”规避了这个问题。 However, please advise what I have done wrong in the script? 但是,请告诉我我在脚本中做错了什么? Thanks. 谢谢。

Try storing the values of your positional paramaters first on an array variable then reset them to 0. "$XILINX/../settings32.sh" may be acting differently when it detects some arguments. 尝试先将位置参数的值存储在数组变量上,然后将其重置为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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM