ulfben

startup.service (exercise)

May 15th, 2020
55
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ###
  2. ### /etc/systemd/system/mystartupscript.service
  3. ###
  4. [Unit]
  5. Description=My Startup Script
  6. Wants=network-online.target
  7. After=network.target network-online.target
  8.  
  9. [Service]
  10. Type=oneshot
  11. ExecStart=/usr/local/bin/my_startup_script.sh
  12. ExecStartPre=/bin/bash -c 'until host http://www.wttr.in; do sleep 1; done'
  13. User=root
  14. Group=root
  15.  
  16. [Install]
  17. WantedBy=multi-user.target
  18.  
  19.  
  20. ###
  21. ### /usr/local/bin/my_startup_script.sh
  22. ###
  23. #!/bin/bash
  24.  
  25. #error handler to exit with useful info
  26. error() {
  27.   local message="$1"
  28.   local code="${2:-1}"
  29.   echo "Error: ${message}; exiting with status ${code}" 1>&2
  30.   exit "${code}"
  31. }
  32.  
  33. #set up the variables - a directory to add to PATH, and a temporary output file
  34. dirname='/opt/myapp/bin:'
  35. outfile='/opt/myapp/weather.txt'
  36. mkdir -p -- "$dirname" || error "Unable to create $dirname" 1;
  37. touch "$outfile" || error "Failed to create $outfile" 1;
  38. chmod 666 "$outfile"
  39.  
  40. #append directory to path
  41. ###avoiding spurious leading/trailing colon if $PATH is initially empty
  42. ###see https://unix.stackexchange.com/a/415028
  43. ##export PATH="${PATH:+${PATH}:}$dirname"
  44. sed -e 's|'${dirname}'||g' -i /etc/environment
  45. sed -e 's|PATH="\(.*\)"|PATH="'${dirname}'\1"|g' -i /etc/environment
  46.  
  47. #add timestamp to output file
  48. date +%F:%T > "$outfile" || error "Unable to prepend timestamp to $outfile";
  49.  
  50. #append weather report to output file
  51. curl -v 'http://wttr.in/Visby' >> "$outfile" || error "Unable to append weather report to $outfile";
RAW Paste Data