我正在上Unix类,这是我的作业的一部分:
对于用户的〜/ 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
从循环运行到循环运行。
如果您的当前目录不是NOT ~/Documents
,则测试这些文件名是错误的,因为这将在当前目录中搜索而不是在预期目录中搜索。
完成任务的更好方法是
for file in ~/Documents/* ; do
...
done
它将设置$file
为查找文件所需的每个完整路径名。
这样做之后,它应该可以工作,但是它很容易出错:一旦路径或文件之一开始包含空格或其他空白字符,它就会落在您的脚上。
放置"
可能包含空格等内容的变量非常重要。几乎没有理由在没有变量的情况下使用它"
。
这有什么区别?
随着[ -f $file ]
,并且file='something with spaces'
,[
被调用的参数-f
,something
,with
,spaces
和]
。这肯定会导致错误的行为。
OTOH,与[ -f "$file" ]
和file='something with spaces'
,[
被调用的参数-f
,something with spaces
和]
。
因此,引用在Shell编程中非常重要。
当然,也适用[ -d "$file" ]
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句