首页 > 解决方案 > 终端无法理解 Bash 脚本;权限被拒绝错误?

问题描述

到目前为止,我的脚本运行良好。当我从终端调用 ./mkproj.sh 时,它显示它有两个参数(我假设是因为我用 $1 和 $2 调用它),然后继续给出以下错误消息:

参数数量 2

mkdir: 无法创建目录 '/archive': 权限被拒绝

mkdir:无法创建目录“/备份”:权限被拒绝

mkdir: 无法创建目录 '/docs': 权限被拒绝

mkdir: 无法创建目录 '/docs': 权限被拒绝

mkdir: 无法创建目录 '/assets': 权限被拒绝

mkdir: 无法创建目录 '/database': 权限被拒绝

mkdir: 无法创建目录'/src': 权限被拒绝

mkdir: 无法创建目录'/src': 权限被拒绝

我检查了我的文件,包括隐藏文件,并且没有名为 myproject.xml 的文件。我还拥有 mkproj.sh 的执行、读取和写入权限。这是我的脚本:

#!/bin/bash
check_for_file()
{
echo "first argument $0"
echo "second argument $1"
echo "third argument $2"
echo "num arguments $#"
if [ $# -eq 0 ]; then
        local testing_file=myproject
        if [ -d "$testing_file" ]; then
                echo "Directory name already exists"
                exit

        else
                mkdir -p "$testing_file"/{archive,backups,docs/{html,txt},assets,database,src/{sh,c}}
        fi
else
        local testing_file=$1

        if [ -d "$testing_file" ]; then
                echo "Directory name already exists"
                exit
        else
                mkdir -p "$testing_file"/{archive,backups,docs/{html,txt},assets,database,src/{sh,c}}
        fi
fi
}

check_for_file "$1" "$2"

谢谢!

标签: bashpermissions

解决方案


似乎您想$testing_file在某个目录中找到,如果找不到任何东西,似乎您想创建一个名为$testing_file.

然后,至少您需要修复您的代码,例如:

if [ -d ./$testing_file ]; then

您需要将testing_file路径更改为相对路径或绝对路径(完整路径)。

在您的原始代码中,您的if条件表达式正在检查$testing_file根目录(/)是否存在。


推荐阅读