# Синхронизация runShellCommand

**URL:** <https://support.wirenboard.com/t/sinhronizacziya-runshellcommand/12546>\
**Category:** Rule Engine\
**Created:** [September 7, 2022, 10:26am UTC](https://support.wirenboard.com/t/sinhronizacziya-runshellcommand/12546 "2022-09-07T10:26:00Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Zeta](https://support.wirenboard.com/user_avatar/support.wirenboard.com/zeta/32/30536_2.png) [@Zeta](https://support.wirenboard.com/u/Zeta)\
**Post date:** [September 7, 2022, 10:26am UTC](https://support.wirenboard.com/t/sinhronizacziya-runshellcommand/12546/1 "2022-09-07T10:26:01Z")

</div>

Добрый день!  
Как отследить, что несколько runShellCommand выполнилось?

Требуется вызвать три команды и по завершении всех трех выполнить одно действие.  
Это возможно?

---

<div class="post-metadata">

**Author:** ![BrainRoot](https://avatars.discourse-cdn.com/v2/letter/b/c2a13f/32.png) [@BrainRoot](https://support.wirenboard.com/u/BrainRoot)\
**Post date:** [September 7, 2022, 3:19pm UTC](https://support.wirenboard.com/t/sinhronizacziya-runshellcommand/12546/3 "2022-09-07T15:19:40Z")

</div>

Добрый день. Код возврата анализировать надо, так, например (обработка exitCode):

> [@Скрипт для пингования хоста](https://support.wirenboard.com/t/skript-dlya-pingovaniya-hosta/7977):
>
> Пингует хост указанное количество раз с установленным интервалом. В случае отсутствия ответов больше указанного кличества подряд - отключает реле на установленное время. Вот код: //05\_25\_test\_03.js //ChangeME! Определим пингуемый адрес var addrString = "10.0.0.164" //Устройство-реле var devRelay="wb-mr6c\_45/K1" //ChangeME! Время между пингами, мс var timeBeetveenPing=3000 //ChangeME! Максимальное количество пропущенных пингов var pingFaultCountMAX = 3 //ChangeME! Время отключенного состоя…

Ну и три команды можно объединить через &&

---

<div class="post-metadata">

**Author:** ![Zeta](https://support.wirenboard.com/user_avatar/support.wirenboard.com/zeta/32/30536_2.png) [@Zeta](https://support.wirenboard.com/u/Zeta)\
**Post date:** [September 19, 2022, 4:44pm UTC](https://support.wirenboard.com/t/sinhronizacziya-runshellcommand/12546/4 "2022-09-19T16:44:08Z")

</div>

Не совсем удобно парсить код ответа от нескольких комманд через &&.

По поводу обработки exitCode не понял. Как это поможет дождаться внутри функции завершения runShellCommand?

---

<div class="post-metadata">

**Author:** ![Explorerol](https://avatars.discourse-cdn.com/v2/letter/e/7ab992/32.png) [@Explorerol](https://support.wirenboard.com/u/Explorerol)\
**Post date:** [October 20, 2022, 2:03pm UTC](https://support.wirenboard.com/t/sinhronizacziya-runshellcommand/12546/5 "2022-10-20T14:03:04Z")

</div>

В колбэк-функции есть параметр exitCode, в котором должент быть результат выполнения всех команд:

```auto
exitCallback: function (exitCode, capturedOutput, capturedErrorOutput) //Функция, в которую попадает вывод

```

---

<div class="post-metadata">

**Author:** ![ilya.v](https://avatars.discourse-cdn.com/v2/letter/i/f9ae1b/32.png) [@ilya.v](https://support.wirenboard.com/u/ilya.v)\
**Post date:** [January 20, 2023, 8:19am UTC](https://support.wirenboard.com/t/sinhronizacziya-runshellcommand/12546/6 "2023-01-20T08:19:01Z")

</div>

Можно в асинхронном по своей природе JavaScript сделать синхронные вызовы через последовательность callback’ов.

Примерно так:

```auto
/*
 * JavaScript sync run shell commands
 *
 * Just call next runShellCommand in current function's callback
 *
 */

var shellCommand1 = "sleep 2",
  shellCommand2 = "ping -c 4 8.8.8.8",
  shellCommand3 = "echo WFT",
  WBT = "@Wiren Board Team, " +
    "send proper Priority/LogLevel from wb-rules to journald";

function runMainBlock () {

  log.info("All shell command have run");
  log.info("==========================");
  log.info("= =");
  log.info("= Have a nice day! =");
  log.info("= =");
  log.info("==========================");

}

function runThirdShellCommand () {

  log.info("Run third command");
  runShellCommand(
    shellCommand3,
    {
      captureOutput: true,
      captureError: true,
      exitCallback: function (exitCode, capturedOutput, capturedErrorOutput) {

        if (exitCode) {

          log.error("Third command failed");
          log.warning(WBT);
          log.info(capturedErrorOutput);

        } else {

          log.info("Third command success");
          log.info(capturedOutput);

          runMainBlock();

        }

      }
    }

  );

}

function runSecondShellCommand () {

  log.info("Run second command");
  runShellCommand(
    shellCommand2,
    {
      captureOutput: true,
      captureError: true,
      exitCallback: function (exitCode, capturedOutput, capturedErrorOutput) {

        if (exitCode) {

          log.error("Second command failed");
          log.warning(WBT);
          log.info(capturedErrorOutput);

        } else {

          log.info("Second command success");
          log.info(capturedOutput);

          runThirdShellCommand();

        }

      }
    }

  );

}

function runFirstShellCommand () {

  log.info("Run first command");
  runShellCommand(
    shellCommand1,
    {
      captureOutput: true,
      captureError: true,
      exitCallback: function (exitCode, capturedOutput, capturedErrorOutput) {

        if (exitCode) {

          log.error("First command failed");
          log.warning(WBT);
          log.info(capturedErrorOutput);

        } else {

          log.info("First command success");
          log.info(capturedOutput);

          runSecondShellCommand();

        }

      }
    }

  );

}

runFirstShellCommand();

```

---

<div class="post-metadata">

**Author:** ![Aleksandr\_Khlebnikov](https://support.wirenboard.com/user_avatar/support.wirenboard.com/aleksandr_khlebnikov/32/16067_2.png) [@Aleksandr\_Khlebnikov](https://support.wirenboard.com/u/Aleksandr_Khlebnikov)\
**Post date:** [September 18, 2024, 1:19pm UTC](https://support.wirenboard.com/t/sinhronizacziya-runshellcommand/12546/7 "2024-09-18T13:19:37Z")

</div>


