在 Ubuntu 16.04 上,我不喜欢在操作系统启动时自动启用 WiFi。灵感来自如何让无线网卡的无线电默认关闭?,我写了一个 silentWiFi.service 作为
[Unit]
Description=Disable Wi-Fi on startup
Before=NetworkManager.service
[Service]
Type=oneshot
ExecStart=/etc/default/silenceWiFi
[Install]
WantedBy=multi-user.target
/etc/default/silenceWiFi 中只有以下几行
#!/bin/sh
/bin/sed -i -re "s/^(WirelessEnabled=).*\$/\1false/" /var/lib/NetworkManager/NetworkManager.state
它按预期工作。
但是,如果我将 silentWiFi.service 中的 ExecStart 行更改为
ExecStart=/bin/sed -i -re '\"s/^(WirelessEnabled=).*\\$/\\1false/\"' /var/lib/NetworkManager/NetworkManager.state
服务总是出错
sudo systemctl status silenceWiFi.service
将产生以下消息
● silenceWiFi.service - Disable Wi-Fi on startup
Loaded: loaded (/lib/systemd/system/silenceWiFi.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Fri 2016-08-26 16:10:46 CST; 10s ago
Process: 20423 ExecStart=/bin/sed -i -re "s/^(WirelessEnabled=).*\$/\1false/" /var/lib/NetworkManager/NetworkManager.state (code=exited, Main PID: 20423 (code=exited, status=1/FAILURE)
Aug 26 16:10:46 Y12 systemd[1]: Starting Disable Wi-Fi on startup...
Aug 26 16:10:46 Y12 sed[20423]: /bin/sed: -e expression #1, char 1: unknown command: `"'
Aug 26 16:10:46 Y12 systemd[1]: silenceWiFi.service: Main process exited, code=exited, status=1/FAILURE
Aug 26 16:10:46 Y12 systemd[1]: Failed to start Disable Wi-Fi on startup.
Aug 26 16:10:46 Y12 systemd[1]: silenceWiFi.service: Unit entered failed state.
Aug 26 16:10:46 Y12 systemd[1]: silenceWiFi.service: Failed with result 'exit-code'.
是否可以将其放入sed
ExecStart 行中,这样就不需要 shell 脚本了(例如,不需要 /etc/default/silenceWiFi 的帮助)。
答案1
是的,只需使用以下行
ExecStart=/bin/sed s/^WirelessEnabled=true/WirelessEnabled=false/ -i /var/lib/NetworkManager/NetworkManager.state
使用 cmd 行“现代”解决方案相反,systemd 不再抱怨。
sudo systemctl status silenceWiFi.service
你会看见
● silenceWiFi.service - Disable Wi-Fi on startup
Loaded: loaded (/lib/systemd/system/silenceWiFi.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Fri 2016-08-26 17:29:12 CST; 4min 31s ago
Process: 2506 ExecStart=/bin/sed s/^WirelessEnabled=true/WirelessEnabled=false/ -i /var/lib/NetworkManager/NetworkManager.state (code=ex
Main PID: 2506 (code=exited, status=0/SUCCESS)
Aug 26 17:29:12 Y12 systemd[1]: Starting Disable Wi-Fi on startup...
Aug 26 17:29:12 Y12 systemd[1]: Started Disable Wi-Fi on startup.