ahmetb/kubectx · warning

failed to load previous namespace from file: %w

Error message

failed to load previous namespace from file: %w

What it means

kubens tracks the previous namespace per context in a file created by NewNSFile(ctx); switchNamespace calls f.Load() to read it (needed for the '-' swap). This error wraps a failure to load that state file — a read or parse problem with the namespace history file, not the kubeconfig. Thrown at cmd/kubens/switch.go:67.

Source

Thrown at cmd/kubens/switch.go:67

}

func switchNamespace(kc *kubeconfig.Kubeconfig, ns string, force bool) (string, error) {
	ctx, err := kc.GetCurrentContext()
	if err != nil {
		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)
		}
	}

View on GitHub (pinned to 12ad6fb22e)

Solutions

  1. Check the kubens state directory exists and is writable: ls -ld ~/.kube/kubens (or the XDG state path) and mkdir -p/chmod if needed
  2. Delete the corrupted per-context namespace file so kubens recreates it (you lose '-' history only)
  3. Verify $HOME is set and points to a writable directory in your shell/container
  4. If running in CI, expect no history file; switch by explicit namespace name instead of '-'

Example fix

// before
kubens -   # fails: state file unreadable
// after
rm ~/.kube/kubens/<context-name-file>   # drop corrupted state
kubens default                          # switch explicitly, history resets
Defensive patterns

Strategy: fallback

Validate before calling

f := NewNSFile(ctx)
if _, err := os.Stat(f.Path()); err != nil {
    // treat as no history instead of failing
}

Try / catch

prev, err := f.Load()
if err != nil {
    // degrade gracefully: proceed with empty prev, disable '-' support
    prev = ""
}

Prevention

When it happens

Trigger: f.Load() errors because the namespace file under ~/.kube/kubens/ (or $XDG state dir) is unreadable due to permissions, corrupted/invalid contents, or the home/state directory is inaccessible.

Common situations: HOME points to a read-only or nonexistent directory (CI containers, chroot); the state file was partially written by a crashed process; a dotfile-sync tool replaced the directory with a symlink to a missing path.

Related errors


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