初めての Bash スクリプトを作成していますが、関数呼び出しで構文の問題が発生しています。
具体的には、次のようにスクリプトを呼び出したいと思います。
sh myscript.sh -d=<abc>
<abc>
固定の親ディレクトリ ( ) 内の特定のディレクトリの名前はどこにありますか~/app/dropzone
。子<abc>
ディレクトリが存在しない場合は、そのディレクトリに移動する前にスクリプトで子ディレクトリを作成する必要があります。ユーザーが-d
引数を使用してスクリプトをまったく呼び出さない場合は、単純な使用法メッセージとともにスクリプトが存在するようにします。これまでのスクリプトでの私の最善の試みは次のとおりです。
#!/bin/bash
dropzone="~/app/dropzone"
# If the directory the script user specified exists, overwrite dropzone value with full path
# to directory. If the directory doesn't exist, first create it. If user failed to specify
# -d=<someDirName>, exit the script with a usage statement.
validate_args() {
args=$(getopt d: "$*")
set -- $args
dir=$2
if [ "$dir" ]
then
if [ ! -d "${dropzone}/targets/$dir" ]
then
mkdir ${dropzone}/targets/$dir
fi
dropzone=${dropzone}/targets/$dir
else
usage
fi
}
usage() {
echo "Usage: $0" >&2
exit 1
}
# Validate script arguments.
validate_args $1
# Go to the dropzone directory.
cd dropzone
echo "Arrived at dropzone $dropzone."
# The script will now do other stuff, now that we're in the "dropzone".
# ...etc.
これを実行しようとすると、次のエラーが表示されます。
myUser@myMachine:~/app/scripts$ sh myscript.sh -dyoyo
mkdir: cannot create directory `/home/myUser/app/dropzone/targets/yoyo': No such file or directory
myscript.sh: 33: cd: can't cd to dropzone
Arrived at dropzone /home/myUser/app/dropzone/targets/yoyo.
どこが間違っているのか、私の一般的なアプローチは正しいのでしょうか? 前もって感謝します!