温馨提示×

centos怎么导入脚本

小樊
54
2026-09-30 12:53:33
栏目: 智能运维

在 CentOS 中“导入脚本”通常有以下几种常见场景,我分别说明:


一、直接运行脚本文件

1. 准备脚本

例如有一个脚本 test.sh:

#!/bin/bash
echo "Hello CentOS"

2. 赋予执行权限

chmod +x test.sh

3. 运行脚本

./test.sh

或

bash test.sh

二、在脚本中“导入”另一个脚本(类似 include)

方法 1:使用 source(推荐)

source ./other.sh

或简写:

. ./other.sh

✅ 特点:

  • 在当前 shell 中执行
  • 变量、函数可直接使用

示例

other.sh

#!/bin/bash
say_hello() {
  echo "Hello"
}

main.sh

#!/bin/bash
source ./other.sh
say_hello

三、开机自动执行脚本(导入到系统)

方法 1:rc.local(简单)

vi /etc/rc.d/rc.local

添加:

/root/test.sh

赋权:

chmod +x /etc/rc.d/rc.local

方法 2:systemd 服务(推荐 CentOS 7+)

vi /etc/systemd/system/myscript.service

内容:

[Unit]
Description=My Script

[Service]
ExecStart=/root/test.sh

[Install]
WantedBy=multi-user.target

启用:

systemctl daemon-reload
systemctl enable myscript.service
systemctl start myscript.service

四、定时执行(crontab)

crontab -e

添加:

* * * * * /root/test.sh

五、从 Windows 上传脚本到 CentOS

使用 scp

scp test.sh root@centos_ip:/root/

或使用 rz / sz

yum install -y lrzsz
rz   # 上传

如果你说的“导入脚本”是指:

  • ✅ 环境变量导入
  • ✅ Docker 导入
  • ✅ 数据库脚本导入
  • ✅ Ansible / Shell 模块

可以告诉我具体场景,我可以给你更精确的命令。

0 踩