linux – Shell识别文件〜但不在〜/ Documents中

前端之家收集整理的这篇文章主要介绍了linux – Shell识别文件〜但不在〜/ Documents中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在上Unix课程,这是我的任务的一部分:

对于用户的〜/ Documents目录中的每个文件和子目录,确定该项是文件还是目录,并使用语句中的文件显示相应的消息.

那么,我写的是这样的:

  1. docs=`ls ~/Documents`
  2. for file in $docs ; do
  3. if [ -f $file ] ; then
  4. echo $file "is a file."
  5. elif [ -d $file ] ; then
  6. echo $file "is a directory."
  7. else
  8. echo $file "is not a file or directory."
  9. fi
  10. done

我的文档目录包括以下文件和目录:

  1. DocList.txt (file)
  2. Letter (file)
  3. mypasswdfile (file)
  4. samples (directory)
  5. things (directory)
  6. touchfile (file)

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

  1. DocList.txt is a file.
  2. Letter is a file.
  3. mypasswdfile is a file.
  4. samples is a directory.
  5. things is a directory.
  6. touchfile is a file.

但是,这是输出

  1. DocList.txt is not a file or directory.
  2. Letter is not a file or directory
  3. mypasswdfile is not a file or directory
  4. samples is not a file or directory
  5. things is not a file or directory
  6. touchfile is not a file or directory

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

最佳答案
你的问题是ls只输出没有路径的文件名.

所以你的$文件获取

  1. DocList.txt
  2. Letter
  3. mypasswdfile
  4. samples
  5. things
  6. touchfile

从循环运行到循环运行.

如果当前目录不是〜/ Documents,则测试这些文件名是错误的,因为这将在当前目录中搜索而不是在目标目录中搜索.

完成任务的更好方法

  1. for file in ~/Documents/* ; do
  2. ...
  3. done

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

在这样做之后,它应该可以工作,但它非常容易出错:一旦你的路径或你的一个文件开始有空格或其他空白字符,它就会落在你的脚上.

将“可能包含某些东西的变量放在空间等周围是非常必要的.几乎没有理由使用变量而没有它的周围”.

这有什么区别?

使用[-f $file]和file =’something with spaces’,[使用参数-f,something,with,spaces和]调用.这肯定会导致错误的行为.

OTOH,带[ – f“$file”],file =’带空格的东西’,[用参数-f调用,带空格的东西和].

所以引用在shell编程中非常重要.

当然,[-d“$file”]也是如此.

猜你在找的Linux相关文章