69 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			Bash
		
	
	
	
	
	
			
		
		
	
	
			69 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			Bash
		
	
	
	
	
	
| #!/bin/bash
 | |
| # tmux-oneshot.sh
 | |
| # Run a single command in a tmux session
 | |
| 
 | |
| # Load config file if it exists
 | |
| SCRIPT_DIR=$(dirname "$0")
 | |
| SCRIPT_NAME=$(basename "$0" .sh)
 | |
| CONFIG_FILE="${SCRIPT_DIR}/${SCRIPT_NAME}.conf"
 | |
| if [ -f "$CONFIG_FILE" ]; then
 | |
|     echo "Loading config from $CONFIG_FILE"
 | |
|     source "$CONFIG_FILE"
 | |
| else
 | |
|     echo "Config file $CONFIG_FILE not found, generating template..."
 | |
|     cat > "$CONFIG_FILE" << 'EOF'
 | |
| # tmux-oneshot.conf
 | |
| # Configuration file for tmux-oneshot.sh
 | |
| 
 | |
| # Session name (leave empty to use first word of command)
 | |
| SESSION=""
 | |
| 
 | |
| # Command to run (leave empty to use command line arguments)
 | |
| COMMAND=""
 | |
| 
 | |
| # Whether to attach to session after running command (0 or 1)
 | |
| ATTACH_SESSION=0
 | |
| EOF
 | |
|     echo "Generated $CONFIG_FILE with default values. Please edit and run again."
 | |
|     exit 0
 | |
| fi
 | |
| 
 | |
| # Validate required variables
 | |
| if [ -z "$SESSION" ] && [ -z "$COMMAND" ]; then
 | |
|     echo "Error: Either SESSION or COMMAND must be set in $CONFIG_FILE" >&2
 | |
|     exit 1
 | |
| fi
 | |
| 
 | |
| # Use command line arguments if provided, otherwise use config
 | |
| if [ $# -gt 0 ]; then
 | |
|     COMMAND="$*"
 | |
|     echo "Using command line arguments: $COMMAND"
 | |
| else
 | |
|     if [ -z "$COMMAND" ]; then
 | |
|         echo "Error: No command provided and COMMAND not set in config" >&2
 | |
|         exit 1
 | |
|     fi
 | |
|     echo "Using config command: $COMMAND"
 | |
| fi
 | |
| 
 | |
| # Use session name from config, or first word of command if not set
 | |
| if [ -z "$SESSION" ]; then
 | |
|     SESSION=$(echo "$COMMAND" | awk '{print $1}')
 | |
| fi
 | |
| 
 | |
| # Create session if missing
 | |
| if ! tmux has-session -t $SESSION 2>/dev/null; then
 | |
|     echo "Creating tmux session: $SESSION"
 | |
|     tmux new-session -d -s $SESSION
 | |
| else
 | |
|     echo "Session $SESSION exists, reusing..."
 | |
| fi
 | |
| 
 | |
| # Send command to session
 | |
| echo "Running command: $COMMAND"
 | |
| tmux send-keys -t $SESSION "$COMMAND" C-m
 | |
| 
 | |
| if [ $ATTACH_SESSION -eq 1 ]; then
 | |
|     echo "Attaching to tmux session: $SESSION"
 | |
|     tmux attach -t $SESSION
 | |
| fi | 
