gpt4 book ai didi

linux - Shell 识别 ~ 但不识别 ~/Documents 中的文件

转载 作者:IT王子 更新时间:2023-10-29 00:32:10 26 4
gpt4 key购买 nike

我正在上 Unix 类(class),这是我作业的一部分:

对于用户的 ~/Documents 目录中的每个文件和子目录,确定该项目是文件还是目录,并使用语句中的文件名显示一条消息。

所以,我写的是这样的:

docs=`ls ~/Documents`

for file in $docs ; do
if [ -f $file ] ; then
echo $file "is a file."
elif [ -d $file ] ; then
echo $file "is a directory."
else
echo $file "is not a file or directory."
fi
done

我的文档目录包括这些文件和目录:

DocList.txt  (file)
Letter (file)
mypasswdfile (file)
samples (directory)
things (directory)
touchfile (file)

所以我认为输出应该是这样的:

DocList.txt is a file.
Letter is a file.
mypasswdfile is a file.
samples is a directory.
things is a directory.
touchfile is a file.

但是,这是输出:

DocList.txt is not a file or directory.
Letter is not a file or directory
mypasswdfile is not a file or directory
samples is not a file or directory
things is not a file or directory
touchfile is not a file or directory

我觉得我应该提一下,如果我将 $docs 变量设置为 `ls ~',它将成功显示我的主目录的内容以及这些项目是文件还是目录。这不适用于我尝试过的其他路径。

最佳答案

你的问题是 ls 只输出没有路径的文件名。

所以你的$file得到了值

DocList.txt
Letter
mypasswdfile
samples
things
touchfile

从循环运行到循环运行。

如果您的当前目录不是 ~/Documents,则测试这些文件名是错误的,因为这会在当前目录中搜索,而不是在预期的目录中搜索。

完成任务的更好方法是

for file in ~/Documents/* ; do
...
done

这会将 $file 设置为查找文件所需的每个完整路径名。

这样做之后,它应该可以工作,但它很容易出错:一旦您的路径或其中一个文件开始包含空格或其他空白字符,它就会落在您的脚上。

" 放在可能包含带有空格等内容的变量周围是非常必要的。几乎没有理由使用没有周围 " 的变量。

这里有什么区别?

使用 [ -f $file ]file='something with spaces'[ 使用参数 调用-fsomethingwithspaces]。这肯定会导致错误的行为。

OTOH,使用 [ -f "$file"]file='something with spaces',调用 [参数 -f带空格的东西]

所以在shell编程中引用是非常必要的。

当然,[ -d "$file"] 也是如此。

关于linux - Shell 识别 ~ 但不识别 ~/Documents 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27193536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com