- Как просмотреть статус службы в Linux с помощью systemctl
- Просмотр статуса сервиса:
- Как просмотреть статус службы под названием nginx
- Понимание состояний службы / модулей systemd
- В настоящее время systemd поддерживает следующие модули
- Чтобы показать все установленные файлы модулей, используйте:
- Linux просмотр статуса службы
- Как вывести список модулей, которые systemd в настоящее время имеет в памяти
- Список systemd/systemctl всех отказавших модулей units/services в Linux
- Что делать, если такой сервис, как nginx, не запущен?
- Как просмотреть источник файла службы / модуля systemd
- Вывод
- Bash get exit code of command on a Linux / Unix
- What is an exit code in bash shell?
- How to find out the exit code of a command
- Bash get exit code of command – How to use exit codes in shell scripts
- How do I set an exit code for my own shell scripts?
- A sample shell script to get the exit code of a command
- Recommend exit code for your shell scripts
- How to deal with the exit codes of all piped commands
- Conclusion
Как просмотреть статус службы в Linux с помощью systemctl
Мы используем systemctl status команду под systemd для просмотра статуса данной службы в операционных системах Linux..
Просмотр статуса сервиса:
Синтаксис команды systemctl следующий
systemctl status
systemctl status
Как просмотреть статус службы под названием nginx
Тип:
$ systemctl status nginx.service
ssh server status
$ systemctl status sshd.service
Lighttpd web server status
$ systemctl status lighttpd.service
Точка (« ● ») использует цвет на поддерживаемых терминалах, чтобы быстро обозначить состояние устройства. Белый цвет указывает на «неактивное» или «деактивированное» состояние. Красный цве т указывает на состояние «сбой» или «ошибка». Зеленый цвет указывает на состояние «активное», «перезагрузка» или «активация».
Понимание состояний службы / модулей systemd
Статус службы Linux зависит от различных состояний, таких как:
Service status | Описание |
---|---|
active (running) | Служба или демон работает в фоновом режиме. Например, веб-сервер sshd или nginx / apache и список для входящего трафика. |
active (exited) | Служба успешно запущена из файла конфигурации. Обычно однократная конфигурация сервисов считывается до выхода из сервиса. Например, сервис AppArmor или Firewall. |
active (waiting) | Наша служба работает, но ожидает события, такого как событие CPUS / печати. |
inactive | Сервис не работает. |
enabled | Служба включается во время загрузки. |
disabled | Служба отключена и не будет запущена при загрузке сервера Linux. |
static | Служба не может быть включена в Linux, но обычно запускается другим модулем systemd автоматически. Другими словами, файл модуля не включен и не имеет условий для разрешения в разделе [Установить] файл модуля. |
masked | Служба полностью отключена, и любая операция запуска на ней всегда заканчивается неудачей. |
alias | Имя службы — это псевдоним. Это означает, что служба является символической ссылкой на другой файл модуля. |
linked | Доступен через одну или несколько символических ссылок на файл модуля (постоянно в /etc/systemd/system/ или временно в /run/systemd/system/), даже если файл модуля может находиться за пределами пути поиска файла модуля |
В настоящее время systemd поддерживает следующие модули
- service : Конфигурация служебного модуля о процессе, который контролируется и контролируется systemd.
- mount : Точка монтирования файловой системы контролируется и контролируется systemd.
- swap : Конфигурация файла подкачки / диска контролируется systemd.
- socket : IPC, сетевой сокет или FIFO файловой системы, управляемый и контролируемый systemd, для активации на основе сокетов.
- target : Он содержит информацию о целевом модуле systemd. Он используется для группирования блоков и как известные точки синхронизации при запуске. Например, graphical.target используется для входа на рабочий стол на основе графического интерфейса пользователя. Точно так же multi-user.target используется серверами, на которых пользователи могут входить в систему с помощью ssh / console.
- device : Устройство, представленное в дереве устройств sysfs / udev. Он включает в себя сетевые и другие устройства.
- automount : Автоматическое монтирование файловых систем
- timer : Cron как модуль systemd для запуска команд и служб в заданном формате даты / времени. Например, обновить прошивку или очистить сеанс, созданный веб-приложениями Python или PHP
- path : Специальный целевой модуль systemd, который устанавливает все модули пути. Например, systemd может выполнять определенные действия в зависимости от пути к файловой системе. Если / etc / foo / modifed предприняли какие-то действия..
- slice : Мы используем срез systemd для изоляции рабочих нагрузок. Они определяют иерархию, в которой размещаются области и услуги. Фактические процессы содержатся в объемах или услугах. Считайте это легким докером. Для каждого слайса могут быть установлены определенные ограничения ресурсов, такие как ограничение ЦП или дискового ввода-вывода, которые применяются ко всем процессам.
- scope : Единицы области видимости не конфигурируются через файлы конфигурации юнитов, а создаются только программно с использованием шинных интерфейсов systemd. Они названы аналогично именам файлов. Единица, имя которой заканчивается на «.scope», относится к единице области видимости. Подразделения областей видимости управляют набором системных процессов. В отличие от единиц обслуживания, единицы области видимости управляют процессами, созданными извне, и не разделяют процессы сами по себе. Основное назначение единиц области видимости — это группировка рабочих процессов системного сервиса для организации и управления ресурсами.
Мы можем перечислить все сервисные единицы следующим образом:
$ sudo systemctl —type=service
Хотите увидеть единицы типа монтирования? Попробуйте:
$ sudo systemctl —type=mount
Отобразить все блоки таймера systemd в вашем Linux:
$ sudo systemctl -t timer
Чтобы показать все установленные файлы модулей, используйте:
$ sudo systemctl list-unit-files
Linux просмотр статуса службы
Введите следующую команду, чтобы просмотреть все службы и состояние модулей в вашей системе Linux с момента загрузки:
$ sudo systemctl
Используйте команду grep command/egrep command чтобы отфильтровать требуемые единицы / службы
$ sudo systemctl | grep ssh
$ sudo systemctl | egrep ‘apache|nginx|lighttpd|php’
Как вывести список модулей, которые systemd в настоящее время имеет в памяти
Выполните следующую команду:
$ sudo systemctl list-units
$ sudo systemctl list-units | more
$ sudo systemctl list-units | grep sshd
$ sudo systemctl list-units —type service
$ sudo systemctl list-units —type timer
Список systemd/systemctl всех отказавших модулей units/services в Linux
$ sudo systemctl list-units —failed
$ sudo systemctl list-units —state failed
$ sudo systemctl list-units —state failed —type service
$ sudo systemctl list-units —state failed —type timer
Что делать, если такой сервис, как nginx, не запущен?
Включите службу systemd:
$ sudo systemctl enable nginx.service
Запустите службу nginx:
$ sudo systemctl start nginx.service
Мы можем остановить или перезапустить службу следующим образом:
$ sudo systemctl stop nginx.service
$ sudo systemctl restart nginx.service
Проверить, включена ли служба или нет, запустить:
$ sudo is-enabled nginx.service
Снова просмотреть статус:
$ sudo status nginx.service
Чтобы увидеть полные выходные данные для проблемы службы -full или -l :
$ sudo status nginx.service -l
$ sudo status openvpn.service —full
Мы может отлаживать и просматривать все сообщения журнала, относящиеся к службе, с помощью команды journalctl:
$ sudo journalctl UNIT=nginx.service
Как просмотреть источник файла службы / модуля systemd
Передайте параметр cat следующим образом:
$ sudo systemctl cat
$ sudo systemctl cat nginx.service
/lib/systemd/system/nginx.service
# Stop dance for nginx
# =======================
#
# ExecStop sends SIGSTOP (graceful stop) to the nginx process.
# If, after 5s (—retry QUIT/5) nginx is still running, systemd takes control
# and sends SIGTERM (fast shutdown) to the main process.
# After another 5s (TimeoutStopSec=5), and if nginx is alive, systemd sends
# SIGKILL to all the remaining processes in the process group (KillMode=mixed).
#
# nginx signals reference doc:
# http://nginx.org/en/docs/control.html
#
[Unit]
Description=A high performance web server and a reverse proxy server
Documentation=man:nginx(8)
After=network.target [Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -q -g ‘daemon on; master_process on;’
ExecStart=/usr/sbin/nginx -g ‘daemon on; master_process on;’
ExecReload=/usr/sbin/nginx -g ‘daemon on; master_process on;’ -s reload
ExecStop=-/sbin/start-stop-daemon —quiet —stop —retry QUIT/5 —pidfile /run/nginx.pid
TimeoutStopSec=5
KillMode=mixed [Install]
WantedBy=multi-user.target
Вывод
Вы узнали о перечислении модулей systemd, включая службы Linux, с помощью команды systemctl. См. Документацию по systemctl или введите следующую команду man:
Источник
Bash get exit code of command on a Linux / Unix
I am a new Linux system user. How do I get the exit code of a command? How do I get the exit code or status of Linux or Unix shell command and store it into a shell variable?
Introduction – Each Linux or Unix shell command returns a status when it terminates normally or abnormally. For example, if backup.sh script is unsuccessful, and it returns a code which tells the shell script to send an e-mail to sysadmin.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash on Linux, macOS or Unix-like OS |
Est. reading time | 2 minutes |
What is an exit code in bash shell?
Every Linux or Unix command executed by the shell script or user has an exit status. Exit status is an integer number. 0 exit status means the command was successful without any errors. A non-zero (1-255 values) exit status means command was a failure.
How to find out the exit code of a command
You need to use a particular shell variable called $? to get the exit status of the previously executed command. To print $? variable use the echo command or printf command:
date
echo $?
date-foo-bar
printf ‘%d\n’ $?
How to get the exit code of a command such as date and date-foo-bar
Bash get exit code of command – How to use exit codes in shell scripts
So how do you store exit status of the command in a shell variable? Simply assign $? to a shell variable. The syntax is:
How do I set an exit code for my own shell scripts?
The exit command cause normal shell script termination. It exits the shell with a status of N. The syntax is:
A sample shell script to get the exit code of a command
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Recommend exit code for your shell scripts
Exit status | Description |
---|---|
1 | Catchall for general errors |
2 | Misuse of shell builtins (according to Bash documentation) |
126 | Command invoked cannot execute |
127 | Command not found |
128 | Invalid argument to exit command |
128+n | Fatal error signal “n” |
130 | Bash script terminated by Control-C |
255* | Exit status out of range |
How to deal with the exit codes of all piped commands
Conclusion
This page showed how to use exit codes on Linux or Unix based system and how to get the exit status/code of command. See man pages by typing the man command or help command:
man bash
help exit
For more info see:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
One of the best Unix exit code tutorial with examples. Thank you. I used it on my macOS macMini desktop.
Hi, I just completed 9 captchas- 18 3×3 grids. I come here for a quick tutorial to remind myself of something I already know, in most cases, for one minute so as not to lose my train of thought. Thank-you! But I don’t have the time for the captchas. Please find another solution to whatever problem you are trying to solve.
Captchas are only needed when posting comments to avoid spam. However, Cloudflare might trigger Captchas when it detects IP address with bad reputation.
Hi Vivek,
Love your site, and I’ve learned a lot from it. It’s a great resource.
I normally use a self-administered proxy/VPN when using a browser for privacy reasons. Unfortunately I can’t control which IP address I get without becoming an ISP or a cloud provider myself. Cloudflare probably sees my IP address and knows that it is in the range for cloud provider X, and not from a company or residential IP address, which triggers the captcha.
So in this case it is unfortunately targetting a normal/not-spamming user. I understand that you are doing this so as to not have to deal with spam or other issues; and my behaviour is probably that of only a tiny percentage of users.
Trade-offs and unintended consequences, right? Anyway, I thought it might be useful to hear from someone for whom this was causing issues. In order to check on this and reply today, I ‘only’ had to do 4 captchas.
Thank you kindly for your excellent website.
Источник