![有没有办法在 bash 命令中为参数打“洞”,然后在最后“填充”?例如“cp [hole] dir < [arg]”所以arg出现在最后?](https://linux22.com/image/212135/%E6%9C%89%E6%B2%A1%E6%9C%89%E5%8A%9E%E6%B3%95%E5%9C%A8%20bash%20%E5%91%BD%E4%BB%A4%E4%B8%AD%E4%B8%BA%E5%8F%82%E6%95%B0%E6%89%93%E2%80%9C%E6%B4%9E%E2%80%9D%EF%BC%8C%E7%84%B6%E5%90%8E%E5%9C%A8%E6%9C%80%E5%90%8E%E2%80%9C%E5%A1%AB%E5%85%85%E2%80%9D%EF%BC%9F%E4%BE%8B%E5%A6%82%E2%80%9Ccp%20%5Bhole%5D%20dir%20%3C%20%5Barg%5D%E2%80%9D%E6%89%80%E4%BB%A5arg%E5%87%BA%E7%8E%B0%E5%9C%A8%E6%9C%80%E5%90%8E%EF%BC%9F.png)
我不确定上面的内容是否有意义,但我在 shell 使用中经常注意到的一个模式如下
我有一个命令可能相当长,并且由于 CLI 的设计,有一个必需的命令。我需要多次运行该命令,通常会改变特定的参数。当然,如果我预先知道所有参数,我可以使用 xargs 或其他东西,但有时情况并非如此......所以我可能有一个像这样的命令
cli -flag -flag X arg arg arg arg
重新运行它很烦人,因为我必须跳回 X。所以,以某种方式执行以下操作会很酷:
cli -flag -flag HOLE arg arg arg arg < X
这样如果我想改变参数,我可以按下并轻松替换 X
这可能吗?
答案1
如果我预先知道所有参数,我可以使用 xargs 或其他东西,但有时情况并非如此
如果你知道所有的论点除了改变的,使其成为函数:
myfunc () { cli -flag -flag "$1" arg arg arg arg ; }
然后使用不断变化的参数调用该函数。
或者你可以使用历史扩展:
$ cli -flag -flag X arg arg arg arg # Run the first time
$ ^X^Y # will replace the first occurrence of X anywhere in the previous command with Y and run it
$ ^Y^Y2 # now replace Y with Y2 in the command that resulted from the above
请注意,历史扩展不会歧视 - 如果您已经my-command asterisk period comma colon
并且想要运行my-command asterisk period apostrophe colon
,则不能使用,^comma^apostrophe
因为这会产生my-apostrophend asterisk period comma colon
.在这种情况下,使用函数会更好。