我目前正在学习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
任何人都可以指导我吗?谢谢。
答案 0 :(得分:2)
这不是它的工作方式。必须事先在脚本或终端中设置环境变量,如
export SIM_DIR=/home/someone/simulations
export TEST_DIR=/home/someone/tests
export LOG_DIR=/home/someone/logs
./run_test2
如果您经常使用这些变量,则可能需要在export
中~/.bashrc
使用这些变量。语法与上例中的export
相同。
答案 1 :(得分:1)
从我的问题/示例中我理解的环境变量不是真正的参数。听起来我觉得你想给一个函数/脚本提供参数,如果你这样做,你可以在$ 1-9中找到你的参数(我认为bash支持更多,不确定),参数的数量存储在$#< / p>
需要两个参数的示例函数:
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