Linux service Command Tutorial for Beginners (with Examples)
The service command lets you run a System V init script. In this tutorial, we will briefly discuss this tool using some easy to understand examples. But before we do that, it’s worth mentioning that all examples here have been tested on an Ubuntu 18.04 LTS machine.
Linux service command
Here are the available syntax for the service command in Linux:
service SCRIPT COMMAND [OPTIONS]service --status-all
service --help | -h | --version
And here’s how the man page explains it:
service runs a System V init script or systemd unit in as predictable an environment as possible,
removing most environment variables and with the current working directory set to /.The SCRIPT parameter specifies a System V init script, located in /etc/init.d/SCRIPT, or the name
of a systemd unit. The existence of a systemd unit of the same name as a script in /etc/init.d
will cause the unit to take precedence over the init.d script. The supported values of COMMAND
depend on the invoked script. service passes COMMAND and OPTIONS to the init script unmodified.
For systemd units, start, stop, status, and reload are passed through to their systemctl/initctl
equivalents.
All scripts should support at least the start and stop commands. As a special case, if COMMAND
is --full-restart, the script is run twice, first with the stop command, then with the start
command.
service --status-all runs all init scripts, in alphabetical order, with the status command. The
status is [ + ] for running services, [ - ] for stopped services and [ ? ] for services
without a status command. This option only calls status for sysvinit jobs.
How to use service command?
The usage of the ‘service’ command line tool isn’t complicated at all. Let’s talk about how you can use this utility when it comes to handling scripts like httpd and sshd.
Here’s how you run a script using service:
service httpd start
Here’s how you stop an already running script using service:
service sshd stop
Here’s how you fetch status for a script:
service httpd status
Here’s how you restart and already-running service:
service sshd restart
Conclusion
Depending on your privileges as Linux user, you may want to run all the above examples using the ‘sudo’ command. To learn more about the ‘service’ command, head to its man page.