How do I make a Bash script that opens tmux, runs multiple lines of commands, then detaches from tmux?
Mia Lopez
I’m trying to make a Bash script that opens tmux and runs a few lines of commands and then detach it so I end up in my terminal after it’s done. How do I solve it? Tried everything.
≈#!/bin/bash
cd ~/data
mkdir $1This is what I got so far. When running my Bash script I type in:
myScript folder_name And now I wanna start a tmux session and run:
screamingfrogseospider \
--crawl $2 \
--headless \
--save-crawl \
--output-folder ~/data/$1 \
--timestamped-output \But how do I make a script that opens up tmux and runs these lines and closes also runs tmux detached so I end up in my terminal window?
11 Answer
This should work:
#!/bin/bash
sessname="newsess"
cd ~/data
mkdir "$1"
# Create a new session named "$sessname", and run command
tmux new-session -d -s "$sessname"
tmux send-keys -t "$sessname" "screamingfrogseospider --crawl $2 --headless --save-crawl --output-folder ~/data/$1 --timestamped-output" Enter
# Attach to session named "$sessname"
#tmux attach -t "$sessname"This creates a tmux session with the name set in variable $sessname - you could also use $1 as session name if you like. It then takes your 2 arguments, creates a tmux session with the given name and runs the command.
To make the script more resilient, you should add checks to see if ~/data/$1 already exist, and not run the mkdir command if it does. You could also check that it has 2 parameters with the right format etc.
By default, it does not attach to the session, so you return back to your shell. Uncomment the last line to attach, or run this manually: (replace newsess if you change the value of $sessname)
tmux attach -t newsessPlease let me know if it works for you.
0