How to get session ID from interactive session?

Resolved 💬 16 comments Opened May 26, 2025 by ronnyli Closed Feb 3, 2026

I had a non-interactive conversation get too long so it stopped accepting new messages until I resumed the session in an interactive terminal and ran /compact. Now I would like to resume my non-interactive conversation but I don't know what session ID to resume from.

View original on GitHub ↗

16 Comments

m7rcelo · 1 year ago

On the underlying issue, the Claude Code SDK documentation indicates that multi-turn conversations are supported in non-interactive mode, but if there's no way to compact a conversation without having to switch to interactive mode, I'm not sure you could really say that it's supported.
I think that either the SDK docs should say that "multi-turn conversations are supported up to the model's context limit" or automatic compact should work in non-interactive mode.

gregor-RW · 12 months ago

Well, running --output-format json we get:

{
  "type": "result",
  "subtype": "success",
  "is_error": false,
  "duration_ms": 7899,
  "duration_api_ms": 7865,
  "num_turns": 1,
  "result": "Looking at ... Cloude Response ...",
  "session_id": "f38b6614-d740-4441-a123-0bb3bea0d6a9",
  "total_cost_usd": 0.08348025,
  "usage": {
    "input_tokens": 3,
    "cache_creation_input_tokens": 21379,
    "cache_read_input_tokens": 0,
    "output_tokens": 220,
    "server_tool_use": {
      "web_search_requests": 0
    },
    "service_tier": "standard"
  }
}```

and the session_id is right there!
coygeek · 11 months ago

That's a great question and a pretty common workflow when you're mixing interactive and non-interactive sessions.

The easiest way to get the current session ID from within an interactive terminal session is to use the /status command.

When you run /status, it gives you a bunch of useful info about your current session, including the ID. It'll look something like this:

> /status

Account Status
  Logged in as: your_email@example.com
  Account type: Console
  Organization: Your Org Name (org-xxxxxxxx)

Session Status
  Session ID: 550e8400-e29b-41d4-a716-446655440000  <-- THIS IS WHAT YOU NEED
  Model: Sonnet 4
  Provider: Anthropic

... and so on

So, your full workflow to solve your problem would be:

  1. Your non-interactive script stops because the context is full.
  2. In your terminal, run claude -c to continue that last session interactively.
  3. Run /compact to shrink the conversation history.
  4. Run /status to get the session ID.
  5. Copy that session ID.
  6. Go back to your script and resume the now-compacted conversation using claude -r "PASTE_THE_SESSION_ID_HERE" -p "Your next prompt...".

---

A Pro-Tip for Future Scripts

For what it's worth, a more robust way to handle this for long-running non-interactive scripts is to capture the session ID from the very first call. You can do this by using the --output-format json flag.

The first time you call claude in your script, you can do this:

# Start the conversation and capture the session ID
initial_output=$(claude -p "This is the very first prompt" --output-format json)
SESSION_ID=$(echo "$initial_output" | jq -r '.session_id')

echo "Started session: $SESSION_ID"

# Now, for all future calls in your script, use that ID
claude -r "$SESSION_ID" -p "This is the second prompt"
claude -r "$SESSION_ID" -p "This is the third prompt"

This way, you always have the session ID handy in a variable ($SESSION_ID) and never have to guess or switch to an interactive terminal to find it.

Hope this helps you out

masszhou · 10 months ago

inspired by @coygeek 's solution, I wrote a script for interactive env.

add a script with chmod +x

#!/bin/bash

SCRIPT_DIR="/Users/<Name>/.claude/dev/scripts"
# Get current system time and format it
CURRENT_TIME=$(date '+%Y-%m-%d %H:%M:%S %Z')
DEFAULT_PROMPT="This session starts from $CURRENT_TIME"

# Get prompt from argument or use default
PROMPT="${1:-$DEFAULT_PROMPT}"

# Start the conversation and capture the session ID
echo "Starting Claude session with prompt: '$PROMPT'"
initial_output=$(claude -p "$PROMPT" --output-format json)

# Check if the command was successful
if [ $? -eq 0 ]; then
    # Clean the output to handle control characters that break jq parsing
    cleaned_output=$(echo "$initial_output" | tr -d '\000-\037')
    SESSION_ID=$(echo "$cleaned_output" | jq -r '.session_id' 2>/dev/null)
    if [ "$SESSION_ID" != "null" ] && [ -n "$SESSION_ID" ]; then
        export SESSION_ID
        echo "Started session: $SESSION_ID"
        echo "Environment variable SESSION_ID has been set: $SESSION_ID"
        claude -r "$SESSION_ID"
    else
        echo "Failed to extract session ID from response"
        echo "Response: $initial_output"
    fi
else
    echo "Failed to start Claude session"
    echo "Make sure 'claude' command is available and properly configured"
fi

then add a alias in you e.g. .zshrc, and source .zshrc

# Claude session starter script
add alias claude_session='~/.claude/dev/scripts/claude_session.sh'

each time when you start claude code with this alias, it will firstly produce a session id from headless mode and update this session id into env variable, where other program in the same shell session can access this

ShanePresley · 9 months ago

I had claude write a UserPromptSubmit hook for me.

It works like this:

> retrieve <this session>

● The session ID for this current session is: 2db6de4e-ad9a-4825-8365-7cafd55080e8/

The Python is pretty straightforward

#!/usr/bin/env python
import json
import sys

try:
    input_data = json.load(sys.stdin)
except json.JSONDecodeError:
    sys.exit(1)

prompt = input_data.get("prompt", "").lower()

# Check if user wants to log work
if "<session info>" in prompt or "<this session>" in prompt:
    # Pass the entire hook payload to Claude
    output = {
        "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": f"Hook payload: {json.dumps(input_data, indent=2)}"
        }
    }
    print(json.dumps(output))

sys.exit(0)

In my case I wrote a custom /slash command to log my work including commands to resume the current claude session. Time will tell how useful that proves to be but the mechanics of the hook work just fine.

github-actions[bot] · 7 months ago

This issue has been inactive for 30 days. If the issue is still occurring, please comment to let us know. Otherwise, this issue will be automatically closed in 30 days for housekeeping purposes.

ShanePresley · 6 months ago

This issue is still occurring, it is still painful, my hook is still filling the gap for me

ShanePresley · 6 months ago

I just noticed on https://code.claude.com/docs/en/cli-reference that you can specify --session-id. I already use a wrapper script for launching claude, I can just bake that into the launcher script, probably even seed the initial prompt with the same value. I still think retrieval is a valuable feature but there are other work arounds.

github-actions[bot] · 5 months ago

This issue has been automatically closed due to 60 days of inactivity. If you're still experiencing this issue, please open a new issue with updated information.

marcindulak · 5 months ago

This issue was closed incorrectly despite recent human comments. This behavior of the bot is reported at https://github.com/anthropics/claude-code/issues/16497. Please upvote that issue, so maybe it gets noticed.

gregor-RW · 5 months ago

The solution for this problem is actually baked in - we don't need to get the session ids, you can just rename it to whatever you want using /rename which will rename the session to what you need so you can just do "--resume YourSessionName" and thats it!

Elijas · 5 months ago

<img width="450" height="96" alt="Image" src="https://github.com/user-attachments/assets/714a833a-bd64-4478-abd0-81d77c3df3b0" />

Another solution is to modify your /statusline (you can ask your claude to do it to include your session id)

In the screenshot d3c979e is my claude session id

cowwoc · 5 months ago

You're missing the point. The agent needs to be able to access its own session ID at runtime in order to make use of it. This is quite important for reading your agent's conversation history across compactions or making workflows safe across concurrent claude code instances.

Inviz · 5 months ago

statusline.sh side-channeling to file and then reading from file works, but it's clunky.

gwpl · 5 months ago

So I see that interactive command /status provides now session id.

github-actions[bot] · 4 months ago

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.