Linux 利用systemd开机自启shell脚本

简介: Linux 利用systemd开机自启shell脚本

1、编写脚本

$ sudo vim /opt/hello.sh

脚本内容:

#!/bin/bash
while true
do
  #打印hello world ,sleep 1 是每隔一秒打印一次
  echo hello world >> /tmp/hello.log
  #打印当前系统时间
  echo $(date +%Y%m%d-%H%M%S)
  sleep 1
done

2、赋予hello.sh 执行权限

$sudo chmod 0755 /opt/hello.sh

3、创建Unit定义文件

在/etc/systemd/system 下


$sudo vim /etc/systemd/system/hello.service

hello.service 内容如下:

[Unit]
Description = hello daemon
[Service]
ExecStart = /opt/hello.sh
Restart = always
Type = simple
[Install]
WantedBy = multi-user.target

Unit中一般分三个部分【Unit/Service/Install】


Unit中主要是对服务的说明,里面有两个参数:Description(用于描述服务),After(用于描述服务启动的依赖);


Sevice中主要是设置运行参数,里面参数的意思:ExecStart (服务的具体运行命令),Restart = always(进程时服务意外故障的时候可以自动重启的模式),Type = simple(表示其余选项均为系统默认);


Install中主要是服务安装的相关设置。


4、把Unit添加进Service

$sudo systemctl list-unit-files --type=service |grep hello

list-unit-files --type 是列出所有启动文件


正常会输出:

hello.service                          disabled

5、启动服务

$sudo systemctl enable hello     # 开机自动启动on

此时参数中的enable换成disable就是禁止开启自动启动

$sudo systemctl start hello   # 单次开机启动

此时参数中的start换成stop就是停止服务

$sudo systemctl status hello   #运行状态确认

6、看脚本运行是否正常

$tailf /tmp/hello.log

tailf是跟踪日志文件


7、重启机器

再次查看第6步的log文件,如果能正常输出,就是成功了

$sudo reboot  #重启
相关文章
|
4天前
|
分布式计算 Hadoop Shell
使用shell脚本实现自动SSH互信功能
使用shell脚本实现自动SSH互信功能
10 1
|
4天前
|
网络协议 Shell Linux
LabVIEW 在NI Linux实时设备上访问Shell
LabVIEW 在NI Linux实时设备上访问Shell
|
5天前
|
Unix Shell Linux
轻松编写 AIX Shell 脚本
轻松编写 AIX Shell 脚本
13 1
|
5天前
|
Shell Linux
【Linux】进程实践项目(更新中) — 自主shell编写
前几篇文章,我们学习进程的相关知识:进程概念,进程替换,进程控制。熟悉了进程到底是个什么事情,接下来我们来做一个实践,来运用我们所学的相关知识。这个项目就是手搓一个shell模块,模拟实现Xshell中的命令行输入。
11 1
|
6天前
|
监控 关系型数据库 Shell
Shell脚本入门:从基础到实践,轻松掌握Shell编程
Shell脚本入门:从基础到实践,轻松掌握Shell编程
|
6天前
|
关系型数据库 MySQL Shell
在Centos7中利用Shell脚本:实现MySQL的数据备份
在Centos7中利用Shell脚本:实现MySQL的数据备份
|
6天前
|
Shell Linux 信息无障碍
5 个有用的 Linux Shell 转义序列
5 个有用的 Linux Shell 转义序列
|
7天前
|
Shell Linux 编译器
C语言,Linux,静态库编写方法,makefile与shell脚本的关系。
总结:C语言在Linux上编写静态库时,通常会使用Makefile来管理编译和链接过程,以及Shell脚本来自动化构建任务。Makefile包含了编译规则和链接信息,而Shell脚本可以调用Makefile以及其他构建工具来构建项目。这种组合可以大大简化编译和构建过程,使代码更易于维护和分发。
26 5
|
8天前
|
Shell 程序员 数据安全/隐私保护
shell 脚本 if-else判断 和流程控制 (基本语法|基础命令)
shell 脚本 if-else判断 和流程控制 (基本语法|基础命令)
|
8天前
|
存储 Shell C语言
shell脚本 编程 变量 基本入门(详解)
shell脚本 编程 变量 基本入门(详解)