スクリプトのcd機能が機能しないのはなぜですか?

スクリプトのcd機能が機能しないのはなぜですか?

ディレクトリを変更してからファイルを検索するスクリプトを作成しました。

#!/bin/bash
model_dir=/mypath

function chdir () {
  cd $1
}
chdir ${model_dir}/config
if [[ ! -s *.cfg ]]
then
  echo `date` "configure file does not exist"
  exit 1
fi

source myscript.sh.

ベストアンサー1

スクリプト(特に内部cdコマンド)は、または同等の機能を使用して呼び出すと正しく機能します。bashsource.

主な問題は、@adonisがすでにコメントで指摘したように、「*.cfg」というファイルが実際に存在しない限り、ディレクトリを正しく変更した後にシェルが終了することです。これは非常に疑わしいです。

*.cfgをパターンとして使用したいようです。期待通りに動作するようにスクリプトを少し変更する方法は次のとおりです。

#!/bin/bash # Note that the shebang is useless for a sourced script

model_dir=/mypath

chdir() { # use either function or (), both is a non portable syntax
  cd $1
}

chdir ${model_dir}/config
if [ ! -s *.cfg ]; then # Single brackets here for the shell to expand *.cfg
  echo $(date) "configure file does not exist"
  exit 1  # dubious in a sourced script, it will end the main and only shell interpreter
fi

おすすめ記事