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はさらに多くのことをサポートしていると思いますが、不明です)。引数の数は$#に格納されます。

2つの引数を期待する関数の例:

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 に答える