【问题标题】:Files read from source folder not being recognized as files or directories从源文件夹读取的文件未被识别为文件或目录
【发布时间】:2021-08-11 10:54:25
【问题描述】:

这是我的代码:

#!/bin/bash

if [ $# -ne 2 ]
then
    echo "USAGE: `basename $0` ./dir_from ./dir_to"
    exit -1
fi

source=$1
destination=$2

if [ ! -d $source ]
then
    echo "ERROR: Source directory doesn't exist."
    exit -1
fi

if [ ! -d $destination ]
then
    mkdir $destination
fi

allFiles=`ls $source`
total=0

for file in $allFiles
do
    echo $file
    fileName="${file%%.*}"
    extension="${file##*.}"
    size=`ls -l $file | awk '{print $6}'`
    echo $size

    if [ -f $file ] && [ "$extension" == "txt" ] && [[ "$fileName" =~ "^[a-z]*$" ]]
    then
        mv "${source}/${file}" "${destination}/${file}.moved_txt"
    fi
done

以下是source 文件夹的内容:

total 8
-rw-r--r-- 1 191128 domain users 32 May 22 15:01 afile.txt
-rw-r--r-- 1 191128 domain users  0 May 22 15:01 pleaseeeee.txt
-rw-r--r-- 1 191128 domain users 17 May 22 15:01 pls.txt

我面临的问题是检查文件是否实际上是文件[ -f $file ] 的测试不起作用。它说它们不是文件。

除了那个条件之外的一切都有效。是的,正确的文件夹在 source 变量中,是的,for 循环从文件夹中吐出所有文件。

如果我尝试测试 -d 以查看它们是否是目录,那也会失败。只有当我否定-f时才会出现,真是奇怪。

它们显然是文件(由- 表示)。我使用命令touch 创建它们,我也尝试使用命令nano 创建它们并输入一些内容。我还尝试从主目录创建文件并将它们移动到我的源文件夹from,看看这是否会改变任何东西,但它没有。现在有一些有趣的事情:如果文件与脚本位于同一目录中,则它可以工作(它们被识别为文件)。

感谢任何想法和cmets。

【问题讨论】:

  • 将您的脚本粘贴到shellcheck.net 以进行验证。
  • if [ $# -ne 2 ]; then echo "USAGE: $(basename $0) ./dir_from ./dir_to"; exit -1; fi不是最佳做法。 (但它太常见了,需要解决!)。如果您退出非零,则您的程序失败。但是您没有打印错误消息。如果打印使用说明,则应退出 0。做出选择。要么将错误消息(使其简短)打印到 stderr 并退出非零,要么将使用语句打印到 stdout 并退出 0。

标签: bash shell terminal sh gnu


【解决方案1】:

我正在回答我自己的问题,因为我发现了自己的错误。我不知道堆栈溢出是否允许这样做,但如果其他人面临同样的错误,如果这个问题留在这里,我将不胜感激。

在我的变量allFiles 中,我只有文件名。我需要连接文件的实际路径。

if [ -f "$source/$file" ]

【讨论】:

  • 我们甚至鼓励您接受您的回答。
猜你喜欢
  • 2013-06-20
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多