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天前
|
Shell Linux
Linux shell编程学习笔记30:打造彩色的选项菜单
Linux shell编程学习笔记30:打造彩色的选项菜单
|
28天前
|
安全 Linux Shell
Linux上执行内存中的脚本和程序
【9月更文挑战第3天】在 Linux 系统中,可以通过多种方式执行内存中的脚本和程序:一是使用 `eval` 命令直接执行内存中的脚本内容;二是利用管道将脚本内容传递给 `bash` 解释器执行;三是将编译好的程序复制到 `/dev/shm` 并执行。这些方法虽便捷,但也需谨慎操作以避免安全风险。
|
2天前
|
监控 Unix Shell
shell脚本编程学习
shell脚本编程
22 12
|
4天前
|
Shell Linux
Linux shell编程学习笔记82:w命令——一览无余
Linux shell编程学习笔记82:w命令——一览无余
|
5天前
|
Shell
shell脚本变量 $name ${name}啥区别
shell脚本变量 $name ${name}啥区别
|
8天前
|
人工智能 监控 Shell
常用的 55 个 Linux Shell 脚本(包括基础案例、文件操作、实用工具、图形化、sed、gawk)
这篇文章提供了55个常用的Linux Shell脚本实例,涵盖基础案例、文件操作、实用工具、图形化界面及sed、gawk的使用。
25 2
|
29天前
|
Shell
Shell脚本有哪些基本语法?
【9月更文挑战第4天】
43 17
|
29天前
|
存储 Unix Shell
shell脚本编程基础
【9月更文挑战第4天】
36 12
|
27天前
|
网络协议 关系型数据库 MySQL
Shell 脚本案例
Shell 脚本案例
36 8
|
28天前
|
Shell Linux 开发工具
linux shell 脚本调试技巧
【9月更文挑战第3天】在Linux中调试shell脚本可采用多种技巧:使用`-x`选项显示每行命令及变量扩展情况;通过`read`或`trap`设置断点;利用`echo`检查变量值,`set`显示所有变量;检查退出状态码 `$?` 进行错误处理;使用`bashdb`等调试工具实现更复杂调试功能。
下一篇
无影云桌面