【问题标题】:Passing arguments to tclsh via bash heredoc通过 bash heredoc 将参数传递给 tclsh
【发布时间】:2018-05-06 20:27:17
【问题描述】:

我有以下测试用例:

#!/bin/bash
tclsh <<EOF
puts "argv=$argv"
EOF

如何将参数传递给 tclsh?参数必须在文件之后(根据 tclsh 的手册页)

SYNOPSIS
    tclsh ?-encoding name? ?fileName arg arg ...?

更新:

首先,我将获取 bash 命令标志并使用它们为 tclsh 创建参数:

tclarg1="....."
tclarg2="....."

然后我将使用 tcl 获得字符串变量:

SCRIPT='
    proc test{arg1 arg2} {
        some tcl commands
    }
    test ???? ????
'

最后我执行那个字符串:

tclsh <<-HERE
${POPUPSCRIPT}
HERE

如何将“tclarg1”和“tclarg2”传递给 tcl 脚本?

字符串可能来自其他来源(通过获取另一个文件),bash 脚本也可以从多个位置/函数执行该字符串。

【问题讨论】:

    标签: bash heredoc tclsh


    【解决方案1】:

    Heredocs 被发送到程序的标准输入,所以你的命令:

    tclsh <<EOF
    puts "argv=$argv"
    EOF
    

    调用不带参数的 tclsh——甚至没有文件名——并将puts "argv=" 写入 tclsh 的标准输入。 (请注意,$argv 由 Bash 处理,因此 tclsh 永远不会看到它。要解决此问题,您需要编写 &lt;&lt;'EOF' 而不是 &lt;&lt;EOF。)

    因此,为了将参数传递给您的 tclsh 脚本,您需要向 tclsh 传递一个文件名参数,以便您的参数可以放在该文件名参数之后。

    由于 heredocs 被发送到程序的标准输入,因此要使用的文件名就是 /dev/stdin

    tclsh /dev/stdin "$tclarg1" "$tclarg2" <<'EOF'
    puts "argv=$argv"
    EOF
    

    请注意,使用这种方法,tclsh 将不再在脚本开头隐式运行您的.tclshrc(因为它仅在它默认从标准输入读取时才这样做,因为不是被给予任何论据)。如果您需要 .tclshrc 中的任何内容,则需要明确地 source 它:

    tclsh /dev/stdin "$tclarg1" "$tclarg2" <<'EOF'
    source ~/.tclshrc
    puts "argv=$argv"
    EOF
    

    【讨论】:

      【解决方案2】:
      #!/bin/bash
      tclsh <<EOF
      puts "argv=$@"
      EOF
      

      【讨论】:

      • 我不想将所有参数传递给 tclsh。我需要准备在 bash 脚本中创建的一组单独的参数。
      • 您能否详细说明用例以及您要实现的目标是什么?
      【解决方案3】:

      这是一个棘手的小问题,因为 heredocs 对它们在命令行中的显示位置非常挑剔。此外,它们最终会作为文件描述符传递给命令,因此需要一些技巧。

      #!/bin/bash
      
      # Get the script into a variable. Note the backticks and the single quotes around EOF
      script=`cat <<'EOF'
      puts "argv=$argv"
      EOF`
      
      # Supply the script to tclsh as a file descriptor in the right place in the command line
      tclsh <(echo $script) "$@"
      

      这似乎做对了。

      bash$ /tmp/testArgPassing.sh a 'b c' d
      argv=a {b c} d
      

      但是,我肯定会始终使用单独的 .tcl 文件,否则会考虑这种事情。参数操作在 Tcl 中至少与在 Bash 中一样容易,并且这样做使各种编辑器也能够提供合理的语法突出显示。

      借助/usr/bin/env,在PATH 上找到正确的tclsh 很容易:

      #!/usr/bin/env tclsh
      puts "argv=$argv"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-27
        • 2015-01-09
        • 2019-02-08
        • 2014-10-04
        • 2022-01-27
        • 2015-07-12
        • 2021-10-05
        相关资源
        最近更新 更多