【发布时间】:2014-11-28 17:30:05
【问题描述】:
我正在上 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 ~',它将成功显示我的主目录的内容以及项目是文件还是目录。这不适用于我尝试过的其他路径。
【问题讨论】:
-
如果您的用户名中有空格,您可能需要在这些 $file 引用周围加上引号。
-
你真的看过
ls ~/Documents的输出了吗? -
~/Documents/呢?
-
提示:你从哪个目录运行这个脚本?
-
没错。这是parsing
ls的失败之一。你应该这样做:for file in ~/Documents/*; do ...