Bash-如何将转义字符打包成字符串中的特殊字符($)?

时间:2013-02-26 03:11:08

标签: bash sed

我在函数调用getpassword()中返回bash变量,返回“apple $ 123123”

FOO=`getpassword`

我想使用包含$ inside的FOO变量并传递到expect程序

 expect -c "\
    set timeout 90
    set env(TERM)
    spawn rdesktop 192.168.11.1
    expect \"Password:\"
    send -- \"'${FOO}\n'\"
    interact
  "
}

由于$ FOO包含美元符号

,因此出现错误
Password: can't read "123": no such variable
    while executing

我该如何解决这类问题?我想的方法是使用sed将转义字符打包到FOO中?

由于

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

# below is purposely on one line -- it sets the FOO env var
# only for the duration of the expect command.
FOO=$(getpassword) expect -c '
    set timeout 90
    set env(TERM) {are you missing something here?}
    spawn rdesktop 192.168.11.1
    expect "Password:"
    send -- "$env(FOO)\r"    # you send '\r' not '\n'
    interact
'

使用单引号可以更容易地编写(和读取)期望脚本(没有所有反斜杠)。测试:

$ getpassword() { echo 'abc$123'; }
$ FOO=$(getpassword) expect -c 'puts "pw=$env(FOO)"'
pw=abc$123
$ echo "> $FOO <"
>  <