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

How to use a shell variable in tmux command?

我正在编写一个 shell 脚本来确定一些变量,例如一个开放的端口。然后它打开一些 tmux windows,其中执行 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 命令似乎没有 "take" 端口变量。

如何让 tmux 获取变量的值?

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

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