“在tmp目录中创建文件夹时权限被拒绝

问题描述 投票:0回答:2

我正在创建一个计算目录和文件数量的脚本。我试图在tmp文件夹中创建一个新文件,在该文件中,通过在该新文件中插入新行来跟踪有多少目录。但是,当我运行脚本时,得到的权限被拒绝'find / tmp / dcount'。

我在此目录中具有r,w,x权限,并且也是所有文件/目录的所有者。

#!/bin/bash

find $1 \( -type d -fprintf /tmp/dcount "\n" \) ,\( -type f -fprintf /tmp/fcount"\n" \)
dirCount=(wc -l /tmp/dcount| cut -d" " -f1)
fileCount=(wc -l /tmp/fcount| cut -d" " -f1)
printf "Directory Count %d" dirCount
printf "File Count %d" fileCount
linux bash
2个回答
0
投票

权限错误可能是因为您试图搜索您无权访问的目录。您对/tmp的使用不应产生任何权限错误。

在任何情况下,都可以简化此脚本。无需将临时输出文件写入/tmp。这是一个简单的版本:

#!/bin/bash

 dirCount=$(find $1 -type d | wc -l)
 fileCount=$(find $1 -type f | wc -l)
 echo Directory Count: $dirCount
 echo File Count: $fileCount

例如,如果此文件存储在名为countstuff的脚本文件中,而您的主目录例如为/home/alice,则可以这样运行此脚本:

 countstuff /home/alice

如果您不需要将结果存储在变量中,而只想显示结果,则可以将该脚本进一步缩短:

#!/bin/bash

echo Directory Count: $(find $1 -type d | wc -l)
echo File Count: $(find $1 -type f | wc -l)

0
投票

您的find命令行对间距的关注不够。您有:

find $1 \( -type d -fprintf /tmp/dcount "\n" \) ,\( -type f -fprintf /tmp/fcount"\n" \)

[您需要在,后面加一个空格,在第二个"\n"之前加一个空格,并且应该在$1周围使用双引号:

find "$1" \( -type d -fprintf /tmp/dcount "\n" \) , \( -type f -fprintf /tmp/fcount "\n" \)

您也不需要\(\)操作数:

find "$1" -type d -fprintf /tmp/dcount "\n" , -type f -fprintf /tmp/fcount "\n"

现在,您需要决定是否将临时文件名弄乱。您可以简单地写:

echo "Directory Count $(find "$1" -type d -print | wc -l)"
echo "File Count $(find "$1" -type f -print | wc -l)"

由于没有临时文件,所以(a)写入此类文件没有文件权限问题,并且(b)脚本完成(或被中断终止)时不必删除它们。

唯一的缺点是在"$1"下对目录层次结构进行了两次扫描。

注意,如果必须保留文件名,则应至少在名称中使用.$$-fprintf /tmp/dcount.$$,以确保程序的并发执行不会相互干扰。为了安全起见(不可预测的名称),您应该使用:

dcount=$(mktemp /tmp/dcount.XXXXXX)
fcount=$(mktemp /tmp/fcount.XXXXXX)
trap "rm -f $dcount $fcount; exit 1" 0 1 2 3 13 15

find "$1" -type d -fprintf "$dcount" "\n" , -type f -fprintf "$fcount" "\n"

echo "Directory Count" $(wc -l <"$dcount")
echo "File Count" $(wc -l <"$fcount")

rm -f "$dcount" "$fcount"
trap 0
© www.soinside.com 2019 - 2024. All rights reserved.