代码之家  ›  专栏  ›  技术社区  ›  Kora K

如何在tmux命令中使用shell变量?

  •  -1
  • Kora K  · 技术社区  · 8 年前

    我正在编写一个shell脚本来确定一些变量,例如一个开放端口。然后它会打开一些tmux窗口,在其中执行python程序。这些python程序应将端口作为命令行参数,如下所示:

    function find_open_port(){
        # Ports between 49152 - 65535 are usually unused.
        port=$(shuf -i '49152-65535' -n '1')
    
        # Then check if port is open
        if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null ; then
            find_open_port
        else
            # There is no service currently running on this port
            return $port
        fi
    }
    
    find_open_port
    echo "Using port: $port"
    
    tmux new-session -d -s '1' 'python server.py -p $port'
    sleep 2
    tmux split-window -v -t '1' 'python client.py -p $port'
    sleep 1
    tmux split-window -h -t '1' 'python client.py -p $port'
    

    如果我将端口确定为一个整数而不是变量,那么它可以工作(例如1025),但我想运行此端口的并行实例,因此我需要随机选择几个不同的端口。tmux命令似乎没有“接受”端口变量。

    如何让tmux获取变量的值?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Jahid Ramsy de Vos    8 年前

    单引号不允许变量扩展,请使用双引号:

    tmux split-window -v -t '1' "python client.py -p $port"