ahmetb/kubectx · warning

No previous namespace found for current context (%s)

Error message

No previous namespace found for current context (%s)

What it means

When the user runs `kubens -`, switchNamespace swaps to the previous namespace recorded in the per-context namespace file. If that file loaded successfully but contains an empty string, there is nothing to swap to and this error is thrown. Thrown at cmd/kubens/switch.go:72.

Source

Thrown at cmd/kubens/switch.go:72

		return "", fmt.Errorf("failed to get current context: %w", err)
	}
	if ctx == "" {
		return "", errors.New("current-context is not set")
	}
	curNS, err := kc.NamespaceOfContext(ctx)
	if err != nil {
		return "", fmt.Errorf("failed to get current namespace: %w", err)
	}

	f := NewNSFile(ctx)
	prev, err := f.Load()
	if err != nil {
		return "", fmt.Errorf("failed to load previous namespace from file: %w", err)
	}

	if ns == "-" {
		if prev == "" {
			return "", fmt.Errorf("No previous namespace found for current context (%s)", ctx)
		}
		ns = prev
	}

	if !force {
		ok, err := namespaceExists(kc, ns)
		if err != nil {
			return "", fmt.Errorf("failed to query if namespace exists (is cluster accessible?): %w", err)
		}
		if !ok {
			return "", fmt.Errorf("no namespace exists with name \"%s\"", ns)
		}
	}

	if err := kc.SetNamespace(ctx, ns); err != nil {
		return "", fmt.Errorf("failed to change to namespace \"%s\": %w", ns, err)
	}
	if err := kc.Save(); err != nil {

View on GitHub (pinned to 12ad6fb22e)

Solutions

  1. Switch to a namespace by name first (kubens <ns>); after that `kubens -` will work
  2. Check you are on the expected context: kubectl config current-context — history is tracked per context
  3. Use the explicit namespace name instead of '-' for this one switch

Example fix

// before
kubens -   # no history for this context
// after
kubens kube-system   # first switch records history
kubens -             # now swaps back
Defensive patterns

Strategy: validation

Validate before calling

if target == "-" {
    prev, _ := NewNSFile(currentCtx).Load()
    if prev == "" {
        return errors.New("no previous namespace recorded; switch by name first")
    }
}

Try / catch

if err := runKubens("-"); err != nil && strings.Contains(err.Error(), "No previous namespace") {
    return runKubens(fallbackNamespace) // e.g. "default"
}

Prevention

When it happens

Trigger: Target is "-" and f.Load() returned ("", nil): no previous namespace has ever been saved for the current context (first switch, or history was wiped).

Common situations: Running `kubens -` right after installing kubens; after switching clusters/contexts (history is per-context); after deleting the kubens state directory; in a fresh container where ~/.kube/kubens does not persist.

Related errors


AI-assisted analysis of ahmetb/kubectx@12ad6fb22e (2026-09-02). Data as JSON: /api/errors/529a62a531a742cc. Report an issue: GitHub.