Skip to main content

Overview

The --prompt (or -p) option runs Qwen Code in non-interactive mode, executing a single prompt and exiting. This is ideal for automation, scripting, and CI/CD pipelines.

Syntax

qwen --prompt "Your prompt here"
qwen -p "Your prompt here"

Basic Usage

Single Command

qwen --prompt "Create a Python function to calculate factorial"
Output:
def factorial(n):
    """Calculate the factorial of n."""
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers")
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

Code Generation

qwen --prompt "Write a REST API endpoint for user authentication"

Code Review

qwen --prompt "Review the code in src/auth.ts for security issues"

Piping Input

Combine stdin with the prompt:
# Read file and append prompt
cat mycode.py | qwen --prompt "Add type hints to this code"

# Git diff review
git diff | qwen --prompt "Review these changes"

# Error analysis
npm test 2>&1 | qwen --prompt "Explain these test failures"
The stdin content is automatically prepended to your prompt.

Output Formats

Text Output (Default)

Human-readable output:
qwen --prompt "Hello" --output-format text

JSON Output

Structured output for parsing:
qwen --prompt "Generate a user model" --output-format json
Output:
{
  "type": "result",
  "isError": false,
  "messages": [
    {
      "role": "assistant",
      "content": "Here's a user model..."
    }
  ],
  "usage": {
    "inputTokens": 123,
    "outputTokens": 456,
    "totalTokens": 579
  },
  "durationMs": 2341
}

Stream JSON Output

Real-time streaming events:
qwen --prompt "Build a React app" --output-format stream-json
Outputs newline-delimited JSON events:
{"type":"system_message","session_id":"abc123",...}
{"type":"assistant_message_start",...}
{"type":"content","value":"I'll help you build a React app..."}
{"type":"tool_call_request","name":"write",...}
{"type":"assistant_message_end",...}
{"type":"result","isError":false,...}

Combining with Other Options

With Model Selection

qwen --prompt "Complex refactoring task" --model qwen-coder-plus

With YOLO Mode

Auto-approve all actions:
qwen --yolo --prompt "Fix all linting errors in the project"

With Session Management

# Continue previous session
qwen --continue --prompt "Now add tests for that function"

# Use specific session
qwen --resume abc123 --prompt "Update the authentication"

With Approval Mode

# Plan only, no execution
qwen --approval-mode plan --prompt "Refactor the codebase"

# Auto-approve edits only
qwen --approval-mode auto-edit --prompt "Update all imports"

Slash Commands in Prompts

You can use slash commands in headless mode:
# Compress context
qwen --prompt "/compress"

# Generate project summary
qwen --prompt "/summary"

# View statistics
qwen --prompt "/stats"
Only certain slash commands work in non-interactive mode. Commands requiring user interaction (like /auth, /model) are not supported.

Automation Examples

CI/CD Pipeline

#!/bin/bash
# .github/workflows/ai-review.sh

set -e

# Get changed files
FILES=$(git diff --name-only origin/main...HEAD)

# Review each file
for file in $FILES; do
  echo "Reviewing $file..."
  qwen --prompt "Review $file for issues" --output-format json > "review-$file.json"
done

# Aggregate results
echo "Review complete. Check review-*.json files."

Code Generation Script

#!/bin/bash
# generate-tests.sh

for file in src/**/*.ts; do
  if [[ ! -f "${file%.ts}.test.ts" ]]; then
    echo "Generating tests for $file"
    qwen --yolo --prompt "Create comprehensive unit tests for $file"
  fi
done

Documentation Generator

#!/bin/bash
# generate-docs.sh

qwen --prompt "Generate API documentation for all files in src/api/" \
     --output-format json \
     | jq -r '.messages[] | select(.role=="assistant") | .content' \
     > API_DOCS.md

echo "Documentation generated in API_DOCS.md"

Error Analyzer

#!/bin/bash
# analyze-errors.sh

# Run tests and capture errors
ERRORS=$(npm test 2>&1 || true)

# Analyze with AI
echo "$ERRORS" | qwen --prompt "Analyze these test failures and suggest fixes" \
                       --output-format text

Interactive vs Non-Interactive

Use --prompt When:

✅ Running in scripts or CI/CD
✅ One-shot commands
✅ Automated workflows
✅ Piping data through Qwen Code
✅ Need programmatic output (JSON)

Use Interactive Mode When:

✅ Exploratory work
✅ Complex, multi-step tasks
✅ Need to approve actions
✅ Iterative development
✅ Want conversation history

Prompt Engineering

Be Specific

# Vague
qwen --prompt "Fix the bug"

# Specific
qwen --prompt "Fix the null pointer exception in src/auth.ts line 45"

Provide Context

# Better with context
qwen --prompt "This is a React TypeScript project. Add error boundaries to all routes."

Use Clear Instructions

qwen --prompt "Do the following:
1. Read all files in src/
2. Find unused imports
3. Remove them
4. Run linter to verify"

Error Handling

Check Exit Codes

qwen --prompt "Do something" && echo "Success" || echo "Failed"

# In scripts
if qwen --prompt "Task" --output-format json > result.json; then
  echo "AI task completed successfully"
else
  echo "AI task failed with exit code $?"
  exit 1
fi

Parse JSON Errors

RESULT=$(qwen --prompt "Task" --output-format json)

if echo "$RESULT" | jq -e '.isError' > /dev/null; then
  ERROR_MSG=$(echo "$RESULT" | jq -r '.errorMessage')
  echo "Error: $ERROR_MSG"
  exit 1
fi

Advanced Usage

Multi-line Prompts

# Using heredoc
qwen --prompt "$(cat <<'EOF'
Create a REST API with the following endpoints:
- GET /users - List all users
- POST /users - Create user
- GET /users/:id - Get user
- PUT /users/:id - Update user
- DELETE /users/:id - Delete user

Use Express.js and TypeScript.
EOF
)"

Prompt from File

# Store complex prompts in files
qwen --prompt "$(cat prompts/generate-api.txt)"

Chaining Commands

# Generate, then test, then commit
qwen --yolo --prompt "Add logging to auth.ts" && \
npm test && \
git add auth.ts && \
git commit -m "Add logging"

Conditional Execution

# Only run if tests fail
npm test || qwen --prompt "Fix the failing tests" --yolo

Output Processing

Extract Code Blocks

qwen --prompt "Create a function" | \
  sed -n '/```python/,/```/p' | \
  sed '1d;$d' > output.py

Parse JSON Output

# Get token usage
qwen --prompt "Task" --output-format json | \
  jq '.usage.totalTokens'

# Get assistant response
qwen --prompt "Question" --output-format json | \
  jq -r '.messages[] | select(.role=="assistant") | .content'

# Check for errors
qwen --prompt "Task" --output-format json | \
  jq -e '.isError == false' > /dev/null

Stream Processing

# Process streaming output
qwen --prompt "Large task" --output-format stream-json | \
  while IFS= read -r line; do
    TYPE=$(echo "$line" | jq -r '.type')
    case $TYPE in
      "content")
        echo "$line" | jq -r '.value'
        ;;
      "tool_call_request")
        echo "Calling tool: $(echo "$line" | jq -r '.name')"
        ;;
    esac
  done

Performance Tips

Use Faster Models

For simple tasks:
qwen --model qwen-turbo --prompt "Quick question"

Limit Output

qwen --prompt "List files in src/ (max 10)" --max-tokens 500

Parallel Execution

# Process multiple files in parallel
find src/ -name '*.ts' | xargs -P 4 -I {} \
  qwen --prompt "Add JSDoc to {}" --yolo

Limitations

No Interactive Features

These features don’t work in headless mode: ❌ Model selection dialog (/model)
❌ Authentication dialog (/auth)
❌ Session picker (--resume without ID)
❌ Manual approval prompts
❌ Terminal UI navigation

Workarounds

# Instead of /model dialog:
qwen --model qwen-coder-plus --prompt "Task"

# Instead of /auth dialog:
qwen --auth-type openai --openai-api-key "$KEY" --prompt "Task"

# Instead of approval prompts:
qwen --yolo --prompt "Task"  # Auto-approve
qwen --approval-mode plan --prompt "Task"  # Plan only

Troubleshooting

No Output

If there’s no output:
# Check if running interactively
qwen --prompt "Test" --output-format text

# Enable debug mode
qwen --debug --prompt "Test"

Hanging

If the command hangs:
# Set timeout (requires timeout command)
timeout 60 qwen --prompt "Task"

# Use Ctrl+C to cancel

Encoding Issues

# Force UTF-8
export LANG=en_US.UTF-8
qwen --prompt "Task with émojis"

See Also

--prompt-interactive

Execute prompt then continue interactively

--yolo

Auto-approve all actions

Headless Mode

Complete guide to headless mode

Output Formats

Working with different output formats