Python Linux解压安装脚本
#!/bin/bash
# 参数处理
# 第一个参数为python版本,3.x的后一位,必填
# 第二个参数为zip文件夹路径,默认为~/Downloads
# 使用示例
# ./install_python.sh -v 12 -d /home/gxc/Downloads
show_help() {
echo "Usage: $0 [options]"
echo " -h, --help 显示帮助信息"
echo " -v, --version 指定python版本,如12代表3.12"
echo " -d, --dir 指定zip文件夹路径,默认为~/Downloads"
echo " -p, --prefix 指定python安装目录,默认为/usr/local/python3x"
echo " -b, --bin 指定python软链接目录,默认为/usr/bin/"
echo " -n, --name 指定python安装目录名,默认为python3x"
}
# 解析参数
while [ "$#" -gt 0 ]; do
case "$1" in
-h|--help)
show_help
exit 0
;;
-v|--version)
v=$2
shift 2
;;
-d|--dir)
zip_dir=$2
shift 2
;;
-p|--prefix)
prefix=$2
shift 2
;;
-b|--bin)
bin=$2
shift 2
;;
-n|--name)
name=$2
shift 2
;;
*)
echo "Unknown option: $1"
show_help
exit 1
;;
esac
done
if [ -z "$v" ]; then
echo "Error: No python3.x version specified, please specify the version, like '12'"
exit 1
fi
python_version="3.$v"
echo "version: $python_version"
zip_dir=${zip_dir:-~/Downloads}
echo "zip dir: $zip_dir"
prefix=${prefix:-/usr/local/python3$v}
bin=${bin:-/usr/bin/}
name=${name:-python3$v}
py_bin=$prefix/install/bin/python$python_version
py_bin_link=$bin$name
echo "link: $py_bin -> $py_bin_link"
# 进入zip_dir
echo "enter $zip_dir"
pushd $zip_dir > /dev/null 2>&1
# 使用find命令搜索最新的.zst文件
fp=$(find . -type f -name "cpython-$python_version*.zst" -printf '%T+ %p\n' | sort | tail -n 1 | cut -d' ' -f2-)
# 检查是否找到了文件
if [ -z "$fp" ]; then
echo "Error: No .zst file found in the directory: $zip_dir"
exit 1
else
echo "The found .zst file is: $fp"
read -p "Do you want to continue? (y/n): " answer
case $answer in
[Yy]* )
echo "Continuing..."
# 在这里添加你想继续执行的命令
;;
[Nn]* )
echo "Exiting..."
exit 0
;;
* )
echo "Invalid input. Exiting..."
exit 1
;;
esac
fi
echo "file: $fp"
# 删除旧的python解压目录
if [ -a 'python' ]
then
echo "dir 'python' exists, remove it"
rm -rf python
fi
# 解压
echo "unzip $fp"
tar xf $fp
# 检查解压后的文件
echo "check unzip file"
if [ ! -d 'python' ]
then
echo "Error: No 'python' directory found in the zip file: $fp"
exit 1
fi
if [ ! -x "./python/install/bin/python$python_version" ]
then
echo "Error: No './python/install/bin/python$python_version' found in the zip file: $fp"
exit 1
fi
# 删除旧的python安装目录
if [ -a $prefix ]
then
echo "remove old python"
sudo rm -rf $prefix
fi
# 移动解压的python到指定目录
echo "move python to $prefix"
sudo mv ./python $prefix
# 创建软链接
echo "link $py_bin -> $py_bin_link"
sudo ln -sf $py_bin $py_bin_link
# 回到原目录
popd > /dev/null 2>&1
echo "finish install python$python_version"