bash 如何在设置别名时转义单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4909944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape single quote while setting aliases
提问by Sumit
Want to create an alias of this command
想创建这个命令的别名
find . -name '*.sh' -exec chmod a+x '{}' \;
and I am not able to escape the single quotes while setting the alias
并且我无法在设置别名时转义单引号
alias mx='find . -name '*.sh' -exec chmod a+x '{}' \;'
Any help is appreciated.
任何帮助表示赞赏。
采纳答案by atx
You could just use double quotes:
你可以只使用双引号:
alias mx="find . -name '*.sh' -exec chmod a+x {} \;"
EDIT: Also, the single quotes 'around the {}is not necessary.
编辑:另外,单引号'周围{}是没有必要的。
回答by cledoux
What you want is a function, not an alias.
你想要的是一个函数,而不是一个别名。
function mx {
find . -name '*.sh' -exec chmod a+x '{}' \;
}
This will have the same effect an alias would have had, avoids any "creative solutions" to make work, and is more flexible should you ever need the flexibility. A good example of this flexibility, in this case, is enabling the user to specify the directory to search, and default to the current directory if no directory is specified.
这将具有与别名相同的效果,避免任何“创造性的解决方案”来工作,并且在您需要灵活性时更加灵活。在这种情况下,这种灵活性的一个很好的例子是允许用户指定要搜索的目录,如果没有指定目录,则默认为当前目录。
function mx {
if [ -n ]; then
dir=
else
dir='.'
fi
find $dir -name '*.sh' -exec chmod a+x '{}' \;
}
回答by Mark
The other answers contain better solutiuons in this (and most) cases, but might you for some reason really want to escape ', you can do '"'"'which actually ends the string, adds a 'escaped by "and starts the string again.
在这种(和大多数)情况下,其他答案包含更好的解决方案,但您可能出于某种原因真的想转义',您可以这样做'"'"',实际上结束字符串,添加'转义"符并再次启动字符串。
alias mx='find . -name '"'"'*.sh'"'"' -exec chmod a+x {} \;'
More info at How to escape single-quotes within single-quoted strings?
更多信息如何在单引号字符串中转义单引号?
回答by mj41
Try
尝试
alias mx=$'find . -name \'*.sh\' -exec chmod a+x \'{}\' \;'
From man bash:
来自man bash:
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:
$'string' 形式的词被特殊处理。单词扩展为字符串,并按照 ANSI C 标准的规定替换反斜杠转义字符。反斜杠转义序列(如果存在)按如下方式解码:
\ backslash
\' single quote
\" double quote
\n new line
...
See example:
见示例:
echo $'aa\'bb'

