Linux检查子目录的文件数量-当子目录搜索不存在时提供错误的变量结果



我创建了一个脚本,该脚本遍历文件的特定子目录,并告诉我以s开头的每个子目录中有多少文件。我的问题发生在搜索和子目录创建失败时。由于某种原因,当此脚本正在搜索的子目录不存在时,它将输出替换为先前创建的另一个变量????

我是用bash为linux写的。

我正在查看下面的子目录…

participantdirectory/EmotMRI 
participantdirectory/EmotMRI/firstfour/
participantdirectory/T1

那么,这就是我应该得到的输出,当子目录存在并且一切正常时。对于所有文件都是一样的(如果正确的话)。

/home/orkney_01/jsiegel/ruth_data/participants/analysis2/1206681446/20090303/14693
16 in firstfour
776 in EmotMRI folder
2 files in T1 folder

对于没有创建子目录的目录,我得到如下输出…

bash: cd: /home/orkney_01/jsiegel/ruth_data/participants/analysis2/2102770508/20090210 /14616/EmotMRI/firstfour/: No such file or directory
/home/orkney_01/jsiegel/ruth_data/participants/analysis2/2102770508/20090210/14616
776 in firstfour
114 in EmotMRI folder
2 files in T1 folder

我认为,因为firstfour是EmotMRI的子目录,当firstfour文件夹还没有创建时,它会用EmotMRI中的扫描号代替这个答案吗?EmotMRI中的扫描次数(在本例中是正确的)。下面是我的脚本。如果发生了这种事,我该如何阻止它?

for d in $(cat /home/orkney_01/jsiegel/ruth_data/lists/full_participant_list_location_may20)
do
    if [ -d "$d" ]
            then
                    gr="failed"
                    er="failed"
                    fr="failed"
                    cd $d/EmotMRI/firstfour/
                    gr=$(ls s*| wc -l)
                     echo " "
                    echo "$d"
                    echo "$gr in firstfour"
                    cd $d/EmotMRI/
                    er=$(ls s*| wc -l)
                    echo "$er in EmotMRI folder"
                    cd $d/T1/
                    fr=$(ls s*| wc -l)
                    echo "$fr files in T1 folder"
                    cd $d/EmotMRI
            else
                    echo "$d is currently not available in directory"
    fi
done
cd /home/orkney_01/jsiegel/ruth_data/
echo "Check complete"

我知道你可能会对这个脚本有很多改进,我是linux的新手。谢谢你的帮助,

目前,无论是否成功更改工作目录,都将gr设置为ls s* | wc -l的输出。当cd失败时,它会将您留在之前所在的目录中。

您可以将cd命令与其他命令组合起来设置gr:

gr=$(cd $d/EmotMRI/firstfour/ && ls s* | wc -l || echo failed)

这样,如果您成功地cd到子目录,gr将被设置为&&之后命令的输出。否则,gr将被设置为||后的命令输出。您可以对er和fr做同样的事情。

您正在获得应该修复的错误消息。Cd正在失败,因为不允许您更改到不存在的目录。您的shell将留在它原来所在的目录中。看起来您知道如何测试目录是否存在,所以您应该多做一些,以避免尝试进入不存在的目录。

最新更新