Linux Bourne shell - 目录可写检查始终返回为“不可写”

时间:2013-04-03 16:02:22

标签: linux shell

当测试目录是否可写时,此函数始终返回True。有人可以向我解释原因吗?只有“目录可写”(到目前为止)失败了。但我希望包含整个功能,以便提供有关事先发生情况的更多详细信息。

此函数接受“before”和“after”字符串,通过用短划线替换所有空格来重命名文件和/或目录。我只是要使用“重命名”功能,但是我需要遵循一个预先构建的骨架脚本。

更新了scipt:

    my_rename()
    {
        echo "Trying: myrename $1 $2"

        # implement this function to my_rename $1 to $2
        # The following error checking must happen:

        # 1. check if the directory where $1 resided is writeable, if not then report an error
        # Is it a directory or a file
        if [ -d $1 ]
        then
            dnam=$1
            ftyp=$"dir"
        else
            # It's a file. Let's get the dirname
            dnam=$(dirname $1)\"
            ftyp=$"file"
        fi

        echo "dnam $dnam"

        # Is the directory writable
        errcd=0
        if [ ! -w "$dnam" ]
        then
            # Not writable. Show an error.
            echo "Directory $dnam is not writable by $(whoami)"
            errcd=1
        fi

        # 2. check if "$2" exists -if it does report and error and don't do the mv command
        if [ "$errcd" -eq 0 ] && ([ -f $2 ] || [ -d $2 ])
        then
            if [ $ftyp = "file" ]
            then
                echo "File $2 already exists"
            else
                echo "Directory $2 already exists"
            fi
            errcd=1
        fi

        # 3. check the status of the mv command and report any errors
        if [ "$errcd" -eq 0 -a -e $2 ]
        then
            exec "mv -f $1 $2"
            if [ $? -gt 0 ]
            then
                echo "Command failed: myrename $1 $2"
            fi
        fi
    }


    bryan@bryan-VirtualBox:~/renametest$ ./script3.sh -f ~/renametest
    Trying: myrename "/home/bryan/renametest/1 2" "/home/bryan/renametest/1-2"
    dnam "/home/bryan/renametest"
    Directory "/home/bryan/renametest" is not writable by bryan

    drwxr-xr-x  3 bryan bryan  4096 2013-04-03 17:10 renametest

1 个答案:

答案 0 :(得分:0)

由于对mark a comment as an answer的功能请求仍然被拒绝,我在此处复制上述解决方案。

Re:-w问题,看上游。如果第一个参数是目录dnam设置为它,但如果它不是目录或不存在,则执行以下操作:dnam = $(dirname $ 1)\“(最终转义为”表明错误。)您显示的输出示例已经过编辑,或者,当转义为“建议”时,您将这些值传递给函数,并使用引号作为值的一部分 - 糟糕的想法,我几乎可以保证您的文件/目录名称系统不包含引号。看起来这个问题就是你调用这个函数,而不是函数.-- William