我正在编写我的第一个 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.
我哪里出错了,我的一般方法是否正确?提前致谢!