Kornshell 中的反斜杠
我正在查看一些 ksh 代码,发现了一行我认为行不通的行。测试代码后,它确实有效,但我不确定为什么。
如果重要的话,这是在 AIX 5.3 系统上运行的。
代码中的行是:
scriptname=$(\basename $0)
我认为它不会工作,因为 basename 前面有反斜杠
命令,但是当我测试 scriptname
变量时,它具有正确的值。
我在命令行上做了一些进一步的测试:
$ echo $(\echo test)
test
$ echo $(\echo \test)
test
$ echo $(\e\c\h\o \test)
test
$ echo `\e\c\h\o \test`
test
$ echo $(\echo "\test")
est
我在命令替换之外尝试了它,但它仍然没有像我想象的那样工作:
$ \echo \testi\ng
testing
$ \echo "\testi\ng"
esti
g
最后一个是唯一对我有意义的一个。
Kornshell 是否只是忽略反斜杠,或者只是将它们转换为反斜杠前面的字符?我假设在命令行的任何位置放置 \n
都是换行符,但显然只有在引号中或 \\n
中才行。
有人可以解释 ksh 在命令行上使用反斜杠做什么吗?
不管怎样,我认为编写我最初质疑的命令的更好方法是:
scriptname=$(basename $0)
而不是:
scriptname=$(\basename $0)
这重要吗?
提前致谢!
I was looking over some ksh code and came across a line I didn't think would work. Upon testing the code, it did work, but I am not sure why.
If it matters, this is running on an AIX 5.3 system.
The line in the code was:
scriptname=$(\basename $0)
I didn't think it would work because of the backslash in front of the basename
command, but when I tested the scriptname
variable, it had the correct value.
I did some further testing on the command line:
$ echo $(\echo test)
test
$ echo $(\echo \test)
test
$ echo $(\e\c\h\o \test)
test
$ echo `\e\c\h\o \test`
test
$ echo $(\echo "\test")
est
I tried it outside of the command subtitution, and it still didn't work like I thought it would:
$ \echo \testi\ng
testing
$ \echo "\testi\ng"
esti
g
The last one is the only one that makes some sense to me.
Does Kornshell just ignore the backslashes, or maybe just convert them to the character in front of the backslash? I assumed that putting a \n
anywhere on the command line would be a newline, but apparently only if it is in quotes, or \\n
.
Can someone explain what ksh does with backslashes on the command line?
Either way, I assume the better way to write the command I originally questioned would be:
scriptname=$(basename $0)
instead of:
scriptname=$(\basename $0)
Does it matter?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果命令名的任何部分被引用,那么 ksh 在选择要执行的内容时将忽略任何别名。
我想这就是原始脚本使用 \basename 的原因。
If any part of a command name is quoted then ksh will ignore any aliases when selecting what to execute.
I presume that is why the original script was using \basename.
我遇到了一个相关但略有不同的情况。我正在编辑一个 shell 脚本,其中包含几个 rm 命令,写为:
我想知道为什么 '\' 位于 rm 之前,并且类似地尝试了它,结果发现它似乎确实有效。根据这个网站 ,这样做是为了防止脚本意外使用别名(例如,如果 rm 的别名为“rm -i”)。因为我首先在 Stack Overflow 上找到了讨论,所以我想我应该添加这一点,以防它对下一个人有所帮助。
I ran into a related but slightly different situation. I am editing a shell script with several rm commands written as:
I was wondering why the '\' was before the rm and similarly tried it only to find that it does seem to work. Per this site, this is done to prevent the script from accidentally using an alias (e.g. if rm is aliased to 'rm -i'). Since I found the discussion on Stack Overflow first, I thought I would add this bit in case it helps the next person out.