Skip to content

Instantly share code, notes, and snippets.

@igricart
Last active October 28, 2020 10:27
Show Gist options
  • Select an option

  • Save igricart/46a1ec25e12fef852a55797e294221ca to your computer and use it in GitHub Desktop.

Select an option

Save igricart/46a1ec25e12fef852a55797e294221ca to your computer and use it in GitHub Desktop.
Gist to create some test files to show the basic functionality of a oneshot systemd service

Test script

create a script file:

touch /tmp/oneshot_example

copy and paste the content from Run script session then run chmod +x /tmp/oneshot_example and sudo /tmp/oneshot_example

Raw example can be found here

Run script

#!/bin/bash

mkdir -p /tmp/foo/

# Setup /tmp/foo/setup-foo.sh
setup_foo_file=/tmp/foo/setup-foo.sh
touch $setup_foo_file
echo "#!/bin/bash" > $setup_foo_file
echo "echo \"Setting up foo ...\"" >> $setup_foo_file
echo "touch /tmp/foo-activated" >> $setup_foo_file
chmod +x $setup_foo_file

# Setup /tmp/foo/teardown-foo.sh
teardown_file=/tmp/foo/teardown-foo.sh
touch $teardown_file
echo "#!/bin/bash" > $teardown_file
echo "echo \"Tearing down foo ...\"" >> $teardown_file
echo "if [ -f /tmp/foo-activated ]; then" >> $teardown_file
echo "    rm /tmp/foo-activated" >> $teardown_file
echo "else" >> $teardown_file
echo "    echo \"Doesnt seem to be up: Skipping ...\"" >> $teardown_file
echo "fi" >> $teardown_file
chmod +x $teardown_file

# Setup /etc/systemd/system/foo.service
service_file=/etc/systemd/system/foo.service
touch $service_file

echo "[Unit]" >> $service_file
echo "Description=Setup foo" >> $service_file
echo "#After=network.target" >> $service_file
echo -en '\n' >> $service_file
echo "[Service]" >> $service_file
echo "Type=oneshot" >> $service_file
echo "ExecStart=/tmp/foo/setup-foo.sh" >> $service_file
echo "RemainAfterExit=true" >> $service_file
echo "ExecStop=/tmp/foo/teardown-foo.sh" >> $service_file
echo "StandardOutput=journal" >> $service_file
echo -en '\n' >> $service_file
echo "[Install]" >> $service_file
echo "WantedBy=multi-user.target" >> $service_file

systemctl daemon-reload
systemctl start foo.service
systemctl stop foo.service

rm /etc/systemd/system/foo.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment