printf中的多次转义

sh/bash/dash/ksh/zsh等Shell脚本
回复
whaha
帖子: 104
注册时间: 2016-07-08 17:43
系统: debian8

printf中的多次转义

#1

帖子 whaha » 2017-04-11 23:41

这个容易理解。

debian8@debian:~$ printf "%-5s\n" "hah"
hah

这个呢? \\n --> \n
debian8@debian:~$ printf "%-5s\\n" "hah"
hah

按照上面的逻辑 \\\n如何解析? \\\n -->\\n --> \n 为何输出 \n(字面),咩有换行?

debian8@debian:~$ printf "%-5s\\\n" "hah"
hah \ndebian8@debian:~$

下面几个,我就菜了。

debian8@debian:~$ printf "%-5s\\\\n" "hah"
hah \ndebian8@debian:~$ printf "%-5s\\\\\n" "hah"
hah \
debian8@debian:~$ printf "%-5s\\\\\\n" "hah"
hah \


请解释一下,bash的这种行为?
科学之子
帖子: 2284
注册时间: 2013-05-26 6:58
系统: Debian 9

Re: printf中的多次转义

#2

帖子 科学之子 » 2017-04-12 2:53

这里不仅printf命令有转义,还要处理shell的转义
printf "\\"其实传给printf的只有一个"\"
printf "\\\\"传给printf的就是两个"\"即"\\"
因为命令参数里如果有'\'的话,在shell里就需要转义,而传给命令的参数是转义之后的结果
whaha
帖子: 104
注册时间: 2016-07-08 17:43
系统: debian8

Re: printf中的多次转义

#3

帖子 whaha » 2017-04-12 7:15

<table>
<tr>
<td></td>
<td>\n</td>
<td>\\n</td>
<td>\\\n</td>
<td>\\\\n</td>
<td>\\\\\n</td>
<td>\\\\\\n</td>
<td>\\\\\\\n</td>
</tr>
<tr>
<td>escaping by "</td>
<td>none</td>
<td>\n</td>
<td>\\n</td>
<td>\\n</td>
<td>\\\n</td>
<td>\\\n</td>
<td>\\\\n</td>
</tr>
<tr>
<td>escaping by printf</td>
<td>newline</td>
<td>newline</td>
<td>\n literally</td>
<td>\n literally</td>
<td>\+newline</td>
<td>\+newline</td>
<td>\\n literally</td>
</tr>
</table>
附件
analyse.png
(9.4 KiB) 已下载 1 次
上次由 whaha 在 2017-04-12 10:45,总共编辑 1 次。
科学之子
帖子: 2284
注册时间: 2013-05-26 6:58
系统: Debian 9

Re: printf中的多次转义

#4

帖子 科学之子 » 2017-04-12 8:23

仔细试了试,虽然我2楼原理说的没问题
但实测发现\n其实并不是转义后传递给程序,而是原样传递给程序,不知为何
viewtopic.php?f=21&t=483475&p=3188783#p3188783
楼主可以试试 echo "xxx"这样输出的就是转义后传递给程序的真实参数
上次由 科学之子 在 2017-04-12 8:59,总共编辑 1 次。
科学之子
帖子: 2284
注册时间: 2013-05-26 6:58
系统: Debian 9

Re: printf中的多次转义

#5

帖子 科学之子 » 2017-04-12 8:54

@whaha
我的问题找到了答案,同时又再次复习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.
用$'xxx'这样的形式转义应该就可以达到您的要求了
PS:
以前从来没用过这种格式就完全忽略了这种用法,原来这才是全能的escape用法
回复