BASH函数用于在打开文件名之前转义文件名中的空格
一段时间以来,我一直在尝试为我的bash配置文件编写一个函数.我要克服的问题是,通常为我提供包含空格的文件路径,在尝试在终端中打开它之前,必须经历并转义所有空格是很痛苦的.
I've been trying to write a function for my bash profile for quite some time now. The problem I'm trying to overcome is I'm usually provided with file paths that include spaces and it's a pain having to go through and escape all the spaces before I try to open it up in terminal.
例如文件->/Volumes/Company/Illustrators/Website Front Page Design.ai
e.g. File -> /Volumes/Company/Illustrators/Website Front Page Design.ai
我最终想要从终端中打开'/Volumes/Company/Illustrators/Website \ Front \ Page \ Design.ai'.
What I'm trying to end up with is '/Volumes/Company/Illustrators/Website\ Front\ Page\ Design.ai' being opened from my terminal.
到目前为止,我已经设法将空格转出,但是随后出现错误文件.....不存在."
So far I've managed to escape the spaces out, but I then get the error "The file ..... does not exist."
到目前为止,我的代码是
My code so far is
function opn { open "${1// /\\ }";}
任何帮助将不胜感激.
要理解的重要一点是语法和文字数据之间的区别.
The important thing to understand is the difference between syntax and literal data.
正确完成后,转义为语法:shell读取并丢弃了转义.也就是说,当您运行
When done correctly, escaping is syntax: It's read and discarded by the shell. That is, when you run
open "File With Spaces"
或
open File\ With\ Spaces
甚至
open File" "With\ Spaces
...引号和转义符由shell解析和删除,执行的实际操作系统调用是这样的:
...the quoting and escaping is parsed and removed by the shell, and the actual operating system call that gets executed is this:
execv("/usr/bin/open", "open", "File With Spaces")
请注意,该syscall的参数中没有任何反斜杠(或文字引号)!如果在数据中加上文字反斜杠,则会导致其运行:
Note that there aren't any backslashes (or literal quotes) in that syscall's arguments! If you put literal backslashes in your data, then you cause this to be run:
/* this is C syntax, so "\\" is a single-character backslash literal */
execv("/usr/bin/open", "open", "File\\ With\\ Spaces")
...并且除非文件名中带有反斜杠,否则该文件将不起作用,并给出您报告的文件不存在"错误.
...and unless there's a file with backslashes in its name, that just doesn't work, giving the "file does not exist" error you report.
所以-只需用您的名字加引号将其打开即可:
So -- just call open with your name in quotes:
open "$1"
...不需要 opn
包装器.
...there's no need for an opn
wrappper.