【问题标题】:How to pass path to xargs command in Linux如何在 Linux 中将路径传递给 xargs 命令
【发布时间】:2020-05-14 21:02:06
【问题描述】:

我有以下代码,它根据时间戳删除目录中的旧文件:

ls -tp | grep -v '/$' | tail -n +2 | xargs -I {} rm -- {}

我正在尝试制作一个可执行脚本,我不想 cd 进入应该运行上述命令的目录,而是简单地传递路径,例如/tmp/backups/ 给它。

我该怎么做?在每个命令后直接附加路径lsgreptailxargsrm

【问题讨论】:

  • 您可能应该not be using ls in the first place。脚本本身可以安全地cd 到您作为参数传入的目录;父 shell 的工作目录不会受到影响。
  • 删除超过 3 天:find <path> -mtime +3 -exec rm -f {} \;find <path> -mtime +3 -delete;
  • @SielaQ 但我只想保留最近的文件。
  • @tripleee 是的,但是我的文件有一个静态模式,不受您提到的问题的影响。传递到ls 的路径对我不起作用。它仍然在父目录中查找。
  • 我没有说将路径传递给ls;我说cd,就像你得到的答案一样。 ls 受到许多问题的影响,包括但不限于将文件名中的特殊字符变成问号或类似字符。

标签: bash grep ls xargs tail


【解决方案1】:

假设你的路径是你脚本的第一个参数,你可以做一个

cd "${1:-/tmp/backups}" # Use the parameter, supply default if none
# Do your cleanup here

如果你之后在原来的工作目录中有更多的事情要做,那就做一个

cd - >/dev/null
# Do what ever you need to do in the original working directory

将stdout重定向到bit bucket的唯一目的是,因为cd -默认打印到stdout它改变到的目录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2013-10-11
    相关资源
    最近更新 更多