如何转义 shell 脚本变量中的字符

How to escape characters in a shell script variable

我一直在尝试在我的一个变量(读取变量)的开头和结尾插入撇号 ('),但没有成功。

代码:

read message
ping  \'$message\'

输出:

bash test.sh
55 55 
ping: 55': Name or service not known

我所期望的:每当我进入

ping '55 55'

显示ping 55 55 : Name or service not known, 不像上面的输出(55')。 另外,当我使用 echo 而不是 ping 时,它可以正常工作;即

echo '55 55'

这会产生您希望看到的结果。

read message
ping "${message}"

不清楚为什么您认为在主机名周围添加文字单引号会有用;主机名中没有单引号。

ping "$message"

message 中的字符串作为单个参数传递给 ping

echo '55 55'

将字符串 55 55 作为单个字符串引用,但 echo 并不能很好地向您展示它实际作为参数传递的内容。可能更好的测试工具是 printf。比较

bash$ message='55 55'
bash$ printf ">>%s<<\n" $message
>>55<<
>>55<<
bash$ printf ">>%s<<\n" "$message"
>>55 55<<
bash$ printf ">>%s<<\n" \'$message\'
>>'55<<
>>55'<<
bash$ printf ">>%s<<\n" '$message'
>>$message<<
bash$ printf ">>%s<<\n" "'$message'"
>>'55 55'<<
bash$ ping "'55 55'"
ping: cannot resolve '55 55': Unknown host
bash$ ping -c 2 '55 55'
PING 55 55 (0.0.0.55): 56 data bytes
ping: sendto: No route to host
Request timeout for icmp_seq 0

--- 55 55 ping statistics ---
2 packets transmitted, 0 packets received, 100.0% packet loss
bash$ ping 55 55
usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize]
            [-g sweepminsize] [-h sweepincrsize] [-i wait]
            [-l preload] [-M mask | time] [-m ttl] [-p pattern]
            [-S src_addr] [-s packetsize] [-t timeout][-W waittime]
            [-z tos] host
       ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait]
            [-l preload] [-M mask | time] [-m ttl] [-p pattern] [-S src_addr]
            [-s packetsize] [-T ttl] [-t timeout] [-W waittime]
            [-z tos] mcast-group
Apple specific options (to be specified before mcast-group or host like all options)
            -b boundif           # bind the socket to the interface
            -k traffic_class     # set traffic class socket option
            -K net_service_type  # set traffic class socket options
            -apple-connect       # call connect(2) in the socket
            -apple-time          # display current time

总而言之,您需要了解句法引号(您用来向 shell 指示某物是单个字符串的引号)和文字引号(作为字符串本身一部分的字符)之间的区别,并且不要引用 shell 中的任何内容),也可能还有单引号(将字符串完全逐字保留在其中的语法引号)和双引号(将字符串分组为一个参数的语法引号,但是允许 shell 对值执行反斜杠处理、变量插值等)。