一键安装nodejs18 ubuntu2204脚本

!/bin/bash
为Ubuntu 22.04安装Node.js 18的一键安装脚本
输出颜色设置
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
打印带颜色的信息函数
print_info() {
echo -e "\({GREEN}[INFO]\){NC} $1"
}
print_warn() {
echo -e "\({YELLOW}[WARNING]\){NC} $1"
}
检查是否以root权限运行
if [ "$EUID" -ne 0 ]; then
print_warn "请以root权限运行此脚本"
exit 1
fi
检查系统版本
if ! grep -q "Ubuntu 22.04" /etc/os-release; then
print_warn "此脚本设计用于Ubuntu 22.04,当前系统可能不兼容"
read -p "是否继续?(y/n): " -n 1 -r
echo
if [[ ! \(REPLY =~ ^[Yy]\) ]]; then
exit 1
fi
fi
print_info "开始安装Node.js 18.x..."
更新包索引
print_info "更新包索引..."
apt update -qq
安装必要的工具
print_info "安装必要的依赖包..."
apt install -y curl gnupg ca-certificates
添加NodeSource仓库
print_info "添加NodeSource仓库..."
mkdir -p /etc/apt/keyrings
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_18.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
更新包索引
print_info "更新包索引..."
apt update -qq
安装Node.js
print_info "安装Node.js 18.x..."
apt install -y nodejs
验证安装
NODE_VERSION=\((node -v) NPM_VERSION=\)(npm -v)
if [[ $NODE_VERSION == v18* ]]; then
print_info "Node.js安装成功!"
print_info "Node.js版本: $NODE_VERSION"
print_info "NPM版本: $NPM_VERSION"
else
print_warn "Node.js安装可能出现问题,请检查错误信息"
exit 1
fi
安装一些常用的全局npm包(可选)
print_info "是否要安装常用的全局npm包?(如yarn, pm2)"
read -p "安装这些包?(y/n): " -n 1 -r
echo
if [[ \(REPLY =~ ^[Yy]\) ]]; then
print_info "安装yarn..."
npm install -g yarn
print_info "安装pm2..."
npm install -g pm2
print_info "全局包安装完成"
fi
print_info "Node.js 18.x 安装完成!"

浙公网安备 33010602011771号