gpt4 book ai didi

linux - Bash脚本函数调用错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:03:17 25 4
gpt4 key购买 nike

我正在编写我的第一个 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.

我哪里出错了,我的一般方法是否正确?提前致谢!

最佳答案

将函数定义移动到脚本的顶部(哈希爆炸下方)。 bash 反对对 validate_args 的未定义(此时)调用。 usage 定义应该在 validate_args 定义之前。

if 测试“[”和“]”中也应该有空格。

    if [ -d "$dropzone/targets/$1" ]

选项 d 的 getopt 测试应该是:

    if [ "$(getopt d "$1")" ]

这是一个适用于我的 validate_args 版本。我还必须更改拖放区,因为在我的 shell 上 ~ 不会在 mkdir 命令中扩展。

dropzone="/home/suspectus/app/dropzone"

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
}

要传递所有参数,请使用 $* 作为参数 -:

  validate_args $*

最后像这样调用脚本让 getopt 正确解析-:

  myscript.sh -d dir_name

关于linux - Bash脚本函数调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16175977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com