Alex028502
Alex028502

Reputation: 3814

How do you capture the output of a closed tmux session or keep the session open after program exits?

if I do this:

tmux new-session -d -s test ls

is there a way to keep the session open after ls exits?

I would like to get the output later with this

tmux capture-pane -pt test

the same way that I can if I have a session that stays open like this

tmux new-session -d -s test "tail -f testfile.txt"

Or is there another way to capture the output of a session that already existed?

Upvotes: 6

Views: 3869

Answers (2)

ardnew
ardnew

Reputation: 2086

tmux has an option remain-on-exit that I use to retain a command's output when the process exits prematurely.

If you need to set this option prior to the existence of the target session (which seems to be your case), then you'll have to set the option globally for the target server.

If you need to set this option prior to the existence of the target server (which may possibly be your case), then you'll have to create an empty server first before creating the session like so:

tmux start-server \; \
  set-option -g remain-on-exit on \; \
  new-session -d -s "test" ls
tmux capture-pane -pt "test"

Another option to keep the pane open actually comes from Windows. Just add a final read command at the end of your shell commands:

tmux new-session -d -s "test" "ls; read"

Or to wait only if the preceding command exited with a non-zero (error) status:

tmux new-session -d -s "test" "ls || read"

The session will close gracefully by sending it an EOF (Ctrl+d) or EOL (Enter), or forcefully with tmux kill-session ....


Also, if the example in your question isn't just hypothetical, then all of this seems a bit overkill to capture the output of ls. Just use file redirection:

ls > capture

Upvotes: 4

jeremysprofile
jeremysprofile

Reputation: 11445

The easiest way would be to create the session without a specific command, and then call the command later. For instance:

tmux new-session -d -s test
tmux send-keys -t test "ls" Enter
tmux capture pane -t test -p

This is an odd use of tmux and it seems like nohup ls &>>~/mylog.out & might better match your goal.

Upvotes: 3

Related Questions