Kora K Kora K - 10 months ago 38
Bash Question

How to use a shell variable in tmux command?

I'm writing a shell script that determines some variables, e.g. an open port. Then it opens some tmux windows, in which python programs are executed. These python programs should take the port as a command line argument, as such:

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
# There is no service currently running on this port
return $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'

If I determine the port as an integer instead of the variable, it works (e.g. 1025), but I want to run parallel instances of this, therefore I need to randomly choose several different ports. The tmux command doesn't seem to "take" the port variable.

How do I get tmux to take the value of the variable?


Single quote doesn't allow variable expansion, use double quote:

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