ahmetb/kubectx · error

HOME or USERPROFILE environment variable not set

Error message

HOME or USERPROFILE environment variable not set

What it means

Sentinel error in kubectxPrevCtxFile: cmdutil.CacheDir() returned an empty string because neither HOME nor USERPROFILE is set in the environment, so the tool cannot locate its cache directory to store/read the previous-context state file (~/.cache/kubectx/kubectx). Swap and switch operations depend on this path.

Solutions

  1. Set the HOME environment variable (USERPROFILE on Windows) before running kubectx
  2. Ensure the shell environment is complete (e.g. in cron/CI set HOME explicitly)
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at cmd/kubectx/state.go:29 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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

Appendix: source

Thrown at cmd/kubectx/state.go:29

// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"github.com/ahmetb/kubectx/internal/cmdutil"
)

func kubectxPrevCtxFile() (string, error) {
	dir := cmdutil.CacheDir()
	if dir == "" {
		return "", errors.New("HOME or USERPROFILE environment variable not set")
	}
	return filepath.Join(dir, "kubectx"), nil
}

// readLastContext returns the saved previous context
// if the state file exists, otherwise returns "".
func readLastContext(path string) (string, error) {
	b, err := os.ReadFile(path)
	if os.IsNotExist(err) {
		return "", nil
	}
	return string(b), err
}

// writeLastContext saves the specified value to the state file.
// It creates missing parent directories.
func writeLastContext(path, value string) error {
	dir := filepath.Dir(path)

View on GitHub (pinned to 12ad6fb22e)