This works for Linux

I have Linux Ubuntu Server


Create a new service file in the systemd directory.
The file name must end with .service.

example

/etc/systemd/system/wifi-connect.service

Add content

[Unit]
Description=Wi-Fi Connection Service
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/sbin/wpa_supplicant -i wlxbcec2304ecfd -c /etc/wpa_supplicant/wpa_supplicant.conf -D nl80211 -B
Restart=always

[Install]
WantedBy=multi-user.target

if you want to run a sh script in a file:

ExecStart=/bin/bash /location/script.sh

you must use a similar line

In my case I run a wpa_supplicant command

Line explanation:

  • [Unit]: This section defines the service unit.
    • Description: A simple description of the service.
    • After=network-online.target: Ensures the service starts after the basic network is online.
    • Wants is used to indicate that the current service “wants” or desires another service to start with it.
    • Wants handles dependencies. It’s used to specify a relationship between services, indicating that one service “wants” another to start with it.
    • If the service (which is a dependency) (wants or weak dependence) does not start for some reason, the .service will not fail.
    • Wants is ideal for optional dependencies that enhance the performance of the service but are not strictly necessary for its startup.
    • If the desired service starts successfully, it will start in parallel or before the current service (wants).
    • Wants is ideal for optional dependencies that enhance the performance of the service but are not strictly necessary for its startup.
    • If we had used a “strong” dependency with Requires, the wifi-connect.service would fail if network-online.target was not started.
  • [Service]: Defines the service process.
    • ExecStart: This is the command that systemd will execute. The -B argument at the end is crucial, as it tells wpa_supplicant to run in the background, returning control to the console.
    • Restart=always: If the service stops for any reason, systemd will attempt to restart it automatically.
  • [Install]: This section is for enabling the service.
    • WantedBy=multi-user.target: Ensures the service starts when the system enters multi-user mode (i.e., when the system boots).

Reload the systemd daemon to recognize the new service file:

sudo systemctl daemon-reload

Enable the service to start automatically at boot:

sudo systemctl enable wifi-connect.service

Start the service right now:

sudo systemctl start wifi-connect.service

Check service status: To make sure everything is working, check the service status.

sudo systemctl status wifi-connect.service

The output should show that the service is active (running). If so, your Wi-Fi will now automatically connect every time you start your server.