简体   繁体   English

使用 rm 和 ls 时无法通过 SSH 删除目录

[英]Cannot remove directories via SSH when use rm and ls

I try to clean release directories when deploying code to the server, but I need to keep at least 5.我在将代码部署到服务器时尝试清理发布目录,但我需要至少保留 5 个。

Now I use this command to do like I mentioned.现在我使用这个命令来做我提到的。

rm -rf $(ls -1t /path/to/deploy/release | tail -n +6)

Everything looks good when I ran this on the server, but It does not work when I try to run via ssh .当我在服务器上运行它时,一切看起来都很好,但是当我尝试通过 ssh 运行时它不起作用。 . . . .

ssh user@123.456.789.100 'rm -rf $(ls -1t /path/to/deploy/release | tail -n +6)'

Anyone please help or suggest me.任何人请帮助或建议我。 What am I do wrong?我做错了什么?

Warning: like all things that involve rm -Rf and "should work", the below may actually delete all files on the computer (since ssh is involved, that's both the local and remote computers), and possibly set your kitchen on fire.警告:就像所有涉及rm -Rf和“应该工作”的事情一样,下面的内容实际上可能会删除计算机上的所有文件(因为涉及ssh ,这既是本地计算机又是远程计算机),并可能使您的厨房着火。 I take no responsibility for damage etc... Backups (stored somewhere other than your kitchen) are always a good thing to have, and maybe you should test with rm -Ri first?我对损坏等不承担任何责任...备份(存储在厨房以外的其他地方)总是一件好事,也许您应该先用rm -Ri测试?

You don't say what the failure is, but one thing I notice is that the ls command will generate a list of filenames in the /path/to/deploy/release directory, but rm will not be running in that directory, so it's going to try to delete files by those names in your home directory instead of /path/to/deploy/release .你没有说失败是什么,但我注意到的一件事是ls命令将在/path/to/deploy/release目录中生成一个文件名列表,但rm不会在该目录中运行,所以它是将尝试删除主目录中这些名称的文件,而不是/path/to/deploy/release This is fairly easy to fix by cd ing into that directory first (although be sure to write the command so if the cd fails, it won't just randomly delete files in the wrong directory).这很容易通过首先cd进入该目录来修复(尽管一定要写命令,所以如果cd失败,它不会只是随机删除错误目录中的文件)。

Another problem is that the command depends on word splitting to turn the output of ls ... | tail ...另一个问题是命令依赖分词来转ls ... | tail ...的输出。 ls ... | tail ... into a list of filenames, which will fail if any filenames contain whitespace and/or wildcards. ls ... | tail ...进入文件名列表,如果任何文件名包含空格和/或通配符,则该列表将失败。 This is trickier to solve, so I'll just ignore the problem and hope it never blows up on you.这个问题比较难解决,所以我会忽略这个问题,希望它永远不会对你造成影响。

Anyway, with the cd fix (and the whitespace bug unfixed), here's what I get:无论如何,通过cd修复(以及未修复的空白错误),这就是我得到的:

ssh user@123.456.789.100 'cd /path/to/deploy/release && rm -Rf $(ls -1t | tail -n +6)'

Again, testing with rm -Ri (and having good backups) is recommended.同样,建议使用rm -Ri (并有良好的备份)进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM