如何在Linux中将路径传递给xargs命令

问题描述 投票:0回答:1

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

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

我正在尝试以此制作可执行脚本,并且我不想将cd插入应该运行上述命令的目录,而只是传递路径,例如/tmp/backups/

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

bash grep ls xargs tail
1个回答
0
投票

假设您的路径是脚本的第一个参数,则可以执行以下操作

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重定向到位存储区的唯一目的是,因为cd -默认情况下会打印到stdout所更改到的目录。

© www.soinside.com 2019 - 2024. All rights reserved.