如何转义定界符 bash 脚本中的字符

qua*_*n3t 4 bash special-characters expect here-document

我有一个 bash 脚本,它读取输入文件并使用heredoc使用expect ssh到服务器,但在转义输入文件中的某些特殊字符时遇到问题。这是我所拥有的..


我有一个名为 input.txt 的文件,其中包含:

1.2.3.4:abcdefg
2.3.4.5:abc$def
Run Code Online (Sandbox Code Playgroud)

我有一个 bash 脚本,如下所示。如果密码不包含字符“$”,它工作正常,但当密码包含“$”时,它会崩溃,因为它将 $ 后面的部分视为变量。

#!/bin/bash

if [ -e "input.txt" ]; then
    while read i; do

/usr/bin/expect <(cat << EOD
set timeout 15
spawn ssh "user@$(echo $i | cut -d: -f 1)"
#######################

expect "yes/no" {
    send "yes\r"
    expect "Password:" { send "$(echo $i | cut -d: -f 2)\r" }
} "Password:" { send "$(echo $i | cut -d: -f 2)\r" }
expect -re "day: $" { send "\r" }
expect ":" { send "\r" }
expect -re "# $" { send "date\r" }
expect -re "# $" { send "exit\r" }
EOD
)
    done < input.txt
fi
Run Code Online (Sandbox Code Playgroud)

当我运行这个并点击第二组IP时,出现以下错误。

spawn ssh user@2.3.4.5

Unauthorized use of this system is prohibited and may be prosecuted
to the fullest extent of the law. By using this system, you implicitly
agree to monitoring by system management and law enforcement authorities.
If you do not agree with these terms, DISCONNECT NOW.

Password: can't read "def": no such variable
    while executing
"send "abc$def\r" "
    invoked from within
"expect "yes/no" {
    send "yes\r"
    expect "Password:" { send "abc$def\r" }
} "Password:" { send "abc$def\r" }"
    (file "/dev/fd/63" line 5)
Run Code Online (Sandbox Code Playgroud)

有人有什么想法吗?我尝试了双引号内的单引号以及我能想到的所有内容,但仍然无法使其工作。提前致谢

Ral*_*edl 5

如果您不想在此处的文档中扩展任何变量,请引用 EOD:

cat << 'EOD'
...
EOD
Run Code Online (Sandbox Code Playgroud)

例如这个文件:

cat <<EOF
test\$literal
var$(echo this)
EOF
Run Code Online (Sandbox Code Playgroud)

产生这个结果:

test$literal
varthis
Run Code Online (Sandbox Code Playgroud)