0

我目前正在学习 bash 编程,但并不真正理解为什么对我来说传递参数不起作用。

我有一个这样的脚本

#!/bin/bash
# the following environment variables must be set before running this script
# SIM_DIR name of directory containing armsim
# TEST_DIR name of the directory containing this script and the expected outputs
# LOG_DIR name of the directory that your output is written to by the run_test2 script
# ARMSIM_VERBOSE set to "-v" for verbose logging or leave unset

# First check the environment variables are set
giveup=0
if [[ ${#SIM_DIR} -eq 0 || ${#TEST_DIR} -eq 0 || ${#LOG_DIR} -eq 0 ]] ; then
    echo One or more of the following environment variables must be set:
    echo SIM_DIR, TEST_DIR, LOG_DIR
    giveup=1
fi

# Now check the verbose flag
if [[ ${#ARMSIM_VERBOSE} != 0 && "x${ARMSIM_VERBOSE}" != "x-v" ]] ; then
    echo ARMSIM_VERBOSE must be unset, empty or set to -v
    giveup=1
fi

# Stop if environment is not set up
if [ ${giveup} -eq 1 ] ; then
    exit 0
fi

cd ${TEST_DIR}
for i in test2-*.sh; do
  echo "**** Running test ${i%.sh} *****"
  ./$i > ${LOG_DIR}/${i%.sh}.log
done

当我运行 .sh 文件并传入 3 个示例参数时,如下所示:-

$ ./run_test2 SIM_DIR TEST_DIR LOG_DIR

它仍然显示:One or more of the following environment variables must be set: SIM_DIR, TEST_DIR, LOG_DIR

有人可以指导我吗?谢谢你。

4

2 回答 2

2

这不是它的预期工作方式。环境变量必须事先在脚本或终端中设置,例如

export SIM_DIR=/home/someone/simulations
export TEST_DIR=/home/someone/tests
export LOG_DIR=/home/someone/logs

./run_test2

如果您经常使用这些变量,您可能希望将export它们放在~/.bashrc. 语法与上export例中的 s 相同。

于 2012-07-03T11:26:41.817 回答
1

从我从您的问题/示例中理解的意义上,环境变量并不是真正的论点。听起来你想给函数/脚本提供参数,如果你这样做,你可以在 $1-9 中找到你的参数(我认为 bash 支持更多,不确定),参数的数量存储在 $#

需要两个参数的示例函数:

my_func() {
    if [ $# -ne 2 ]; then
        printf "You need to give 2 arguments\n"
        return
    fi

    printf "Your first argument: %s\n" "$1"
    printf "Your second argument: $s\n" "$2"
}

# Call the functionl like this
my_func arg1 arg2
于 2012-07-03T11:58:53.417 回答