Python - Switch between versions

if [ $# -lt 1 ]; then
    echo -e "Usage: $(basename $0) PYTHON_VERSION\n"
    exit 1
fi

BIN_DIR=$(realpath ~/bin)
mkdir -p $BIN_DIR

PYTHON=$(which python$1)
if [[ "$PYTHON" ]]; then
    ln -s $PYTHON $BIN_DIR/python -f
else
    echo "Error: python for v$1 cannot be found."
    exit 2
fi

PIP_VER=$(echo $1 | cut -d '.' -f1)
case "$PIP_VER" in
    2)
        PIP=pip
        ;;
    *)
        PIP=pip$PIP_VER
        ;;
esac

PIP=$(which $PIP)
if [[ "$PIP" ]]; then
    ln -s $PIP $BIN_DIR/pip -f
else
    echo "Error: pip for v$1 cannot be found."
    exit 3
fi
  • 测试
$ python-switch.sh 3.6
$ ll bin
total 0
drwxr-xr-x 1 yuwu yuwu 4096 Aug 21 16:10 ./
drwxr-xr-x 1 yuwu yuwu 4096 Aug 21 16:06 ../
lrwxrwxrwx 1 yuwu yuwu   13 Aug 21 16:10 pip -> /usr/bin/pip3*
lrwxrwxrwx 1 yuwu yuwu   18 Aug 21 16:10 python -> /usr/bin/python3.6*
$ python-switch.sh 2.7
$ ll bin
total 0
drwxr-xr-x 1 yuwu yuwu 4096 Aug 21 16:10 ./
drwxr-xr-x 1 yuwu yuwu 4096 Aug 21 16:06 ../
lrwxrwxrwx 1 yuwu yuwu   12 Aug 21 16:10 pip -> /usr/bin/pip*
lrwxrwxrwx 1 yuwu yuwu   18 Aug 21 16:10 python -> /usr/bin/python2.7*