Shell scripts can't `cd` for you — source them instead

A shell script always runs in a subshell. Any cd it executes vanishes when the script exits — the calling shell's working directory is unchanged.

The fix: source the script instead of executing it. Sourcing runs the script in the current shell, so cd sticks.

alias sw='. ~/bin/sw'

Two things to update in the script itself.

First, replace every exit with return. exit in a sourced script exits the entire shell, not just the script:

exit 1  →  return 1

Second, $0 in a sourced script is the shell binary (bash), not the script path. Use ${BASH_SOURCE[0]} wherever you need the script's own location:

source "$(dirname "${BASH_SOURCE[0]}")/git-common.sh"
script_name=$(basename "${BASH_SOURCE[0]}")

The one tradeoff: functions defined inside the script leak into the shell's namespace after it returns. For a personal utility this is usually fine.

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.