touch all folders in a directory

jav*_*y79 17 bash touch

I am trying to update the timestamps of all folders in the cwd using this:

for file in `ls`; do touch $file; done
Run Code Online (Sandbox Code Playgroud)

But it doesn't seem to work. Any ideas why?

Mic*_*zek 26

到目前为止的所有答案(以及您在问题中的示例)都假设您想要touch目录中的所有内容,即使您说的是“触摸所有文件夹”。如果事实证明该目录包含文件和文件夹,而您只想更新文件夹,则可以使用find

$ find . -maxdepth 1 -mindepth 1 -type d -exec touch {} +
Run Code Online (Sandbox Code Playgroud)

或者,如果您的find实现不支持非标准-mindepth/-maxdepth谓词:

$ find . ! -name . -prune -type d -exec touch {} +
Run Code Online (Sandbox Code Playgroud)

这个:

$ touch -c -- */
Run Code Online (Sandbox Code Playgroud)

应该在大多数 shell 中工作,除了:

  • 除了普通目录之外,它还将touch 符号链接到目录
  • 它会忽略隐藏的
  • 如果没有目录或符号链接的目录,它会创建一个名为*比其他炮弹cshtcshzshfish或者汤普森外壳(这反而会报告一个错误)。在这里,我们正在使用-c它来解决它,尽管这仍然可能是touch一个名为*.

使用zsh,touch仅指向目录,包括隐藏的目录:

touch -- *(D/)
Run Code Online (Sandbox Code Playgroud)

  • `{} \+` 是特殊的 `find` 语法 - 阅读手册页了解更多信息。我认为 `touch -c ./*/` 也可以。 (3认同)
  • 你应该在命令中包含 `-maxdepth 1`,这样 `find` 就不会递归到子文件夹中。OP 似乎只想触摸 cwd 中的那些文件夹,而不是子文件夹。 (2认同)

jw0*_*013 12

尝试

touch ./*
Run Code Online (Sandbox Code Playgroud)

它避免了不必要的for循环,该循环会为每个文件产生一个新进程并适用于所有文件名,即使是带有空格或看起来像选项的文件名(如-t)。它唯一不起作用的情况是目录中没有(非点)文件,在这种情况下,您最终会创建一个名为*. 为了避免这种情况,对于touch大多数实现的特定情况,有一个-c选项(--no-create在 GNU 版本中也称为)不创建不存在的文件,即

touch -c ./*
Run Code Online (Sandbox Code Playgroud)

另请参阅jasonwryan's answer和 this one 中的优秀参考资料。


jas*_*yan 7

You shouldn't attempt to parse the output of ls.

Also, you should quote your "$file" to capture any whitespace. See http://www.grymoire.com/Unix/Quote.html

Something like this might achieve what you are after:

for file in *; do touch "$file"; done
Run Code Online (Sandbox Code Playgroud)

See the first two Bash Pitfalls for a more thorough explanation.

  • 关闭但不完全。`touch ./*` 应该在大多数情况下工作。真的不需要 `for` 循环,因为 `touch` 可以接收多个文件,并且你需要 `./` 来正确处理名称类似于 `--help` 的文件。这是关于该主题的一个很好的 [资源](http://www.dwheeler.com/essays/filenames-in-shell.html)。 (2认同)