简单的 bash 脚本给我带来了问题
我很难让这个 bash 脚本执行输入的格式化。 它非常简单,但是当它执行以 'newstring=' 开头的行时,它不会执行 sed 操作,它只打印我的输入(直到第一个空格),然后直接打印我的 sed 命令。我做错了什么?
#! /bin/bash
##format paths/strings with spaces to escape the spaces with a forward-slash'\'
##then use 'open' to open finder at current-set directory (based on path)
oldstring="$1"
newstring="$oldstring | sed 's/ /\\ /g')"
cd $newstring
open .
I'm having difficulty getting this bash script to perform the formatting of an input.
It's pretty straight-forward, but when it executes the line that starts with 'newstring=', it doesn't perform the sed operation, it only prints my input (up until the first white-space) then prints my sed command directly after. What am I doing wrong?
#! /bin/bash
##format paths/strings with spaces to escape the spaces with a forward-slash'\'
##then use 'open' to open finder at current-set directory (based on path)
oldstring="$1"
newstring="$oldstring | sed 's/ /\\ /g')"
cd $newstring
open .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该简单地这样做:
这可以避免运行子进程并处理
sed
脚本不处理的各种问题(例如包含$
符号或其他 shell 元字符的名称) 。通常,如果变量(或位置参数,例如$1
)是可能包含空格的文件名,则每次都使用双引号括起来。You should simply do:
This avoids running sub-processes and deals with various problems that the
sed
script doesn't (such as names containing$
symbols, or other shell metacharacters). Generally, if a variable (or positional parameter such as$1
) is a file name that could contain spaces, use it surrounded by double quotes every time.尝试将命令放在反引号中,例如
Try putting the command in backquotes like
@Jonathan Leffler 是正确的解决方案,因为添加转义符实际上并不能达到您想要的效果,但双引号却可以。不过,我会借此机会指出,有一种更好的方法可以使用 bash 的内置替换功能而不是 sed 来添加转义符:
所以你已经知道了,这是一种更好的方法来实现错误解决方案。就我个人而言,我投票给乔纳森。
@Jonathan Leffler's is the correct solution, since adding escapes doesn't actually do what you want but double-quoting does. However, I'll take this opportunity to point out that there's a better way to add escapes using bash's built-in substitution capability instead of
sed
:So there you have it, a better way to implement the wrong solution. Personally, I voted for Jonathan's.