bash:传递带有空格作为参数的路径?
我有一个 bash 脚本,它从用户接收一组文件。这些文件有时位于名称中带有空格的目录下。不幸的是,与这个问题不同,所有文件名都是通过命令行界面传递的。假设用户传入的路径被正确引用,因此空格(除了引用的空格之外)是路径之间的分隔符。我如何以保留引用空格的方式将这些参数转发到 bash 脚本中的子例程?
I have a bash script that recieves a set of files from the user. These files are sometimes under directories with spaces in their names. Unfortunately unlike this question all the filenames are passed via the command line interface. Let's assume the paths are correctly quoted as they are passed in by the user, so spaces (save for quoted spaces) are delimiters between paths. How would I forward these parameters to a subroutine within my bash script in a way that preserves the quoted spaces?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请注意过度使用引号。这都是必要的。
将所有参数传递给另一个程序甚至更简单:
棘手的情况是当您想将参数分成两半时。这需要在简单的 POSIX shell 中编写更多代码。但也许 Bash 有一些特殊功能。
Note the excessive use of quotes. It's all necessary.
Passing all the arguments to another program is even simpler:
The tricky case is when you want to split the arguments in half. That requires a lot more code in a simple POSIX shell. But maybe the Bash has some special features.
您需要
"$@"
,它具有扩展$@
但保留调用者的空白引用的特殊语法(它不会创建一个带有其中的所有参数)。因此,有人可以这样调用您的脚本:然后在您的脚本中您可以执行以下操作:
并获得两行输出(而不是 5 行)。
在此处阅读有关特殊参数“@”的段落:http:// /www.gnu.org/s/bash/manual/bash.html#特殊参数
You want
"$@"
, which has the special syntax of expanding$@
but preserving the white-space quoting of the caller (it does not create a single giant string with all the arguments in it). So someone can call your script like:Then in your script you can do things like:
and get two lines of output (not 5).
Read the paragraph about the Special Parameter "@" here: http://www.gnu.org/s/bash/manual/bash.html#Special-Parameters
太棒了 @Roland 。非常感谢您的解决方案
它确实有效!
我编写了一个简单的脚本函数,用 nautilus 打开给定的路径。
我刚刚将一个带有此“helper”-for-loop 的函数嵌套到主函数中:
现在我可以使我的所有脚本都可以处理路径,只需将它们转换为由带有此 helper 的函数包装的嵌套函数-for循环。
Bravo @Roland . Thans a lot for your solution
It has really worked!
I wrote a simple script function that opens a given path with nautilus.
And I've just nested a function with this "helper"-for-loop into the main function:
Now I'm able to make all my scripts work handling with paths just by turning them into nested functions wrapped by a function with this helper-for-loop.
例如,
For example,