Exec cmd in linux

Exec cmd in linux

NAME

exec - execute commands and open, close, or copy file descriptors

SYNOPSIS

exec [command [argument . ]] 

DESCRIPTION

The exec utility shall open, close, and/or copy file descriptors as specified by any redirections as part of the command. If exec is specified without command or arguments, and any file descriptors with numbers greater than 2 are opened with associated redirection statements, it is unspecified whether those file descriptors remain open when the shell invokes another utility. Scripts concerned that child shells could misuse open file descriptors can always close them explicitly, as shown in one of the following examples. If exec is specified with command, it shall replace the shell with command without creating a new process. If arguments are specified, they shall be arguments to command. Redirection affects the current shell execution environment.

OPTIONS

OPERANDS

STDIN

INPUT FILES

ENVIRONMENT VARIABLES

ASYNCHRONOUS EVENTS

STDOUT

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

EXTENDED DESCRIPTION

EXIT STATUS

If command is specified, exec shall not return to the shell; rather, the exit status of the process shall be the exit status of the program implementing command, which overlaid the shell. If command is not found, the exit status shall be 127. If command is found, but it is not an executable utility, the exit status shall be 126. If a redirection error occurs (see Consequences of Shell Errors ), the shell shall exit with a value in the range 1-125. Otherwise, exec shall return a zero exit status.

CONSEQUENCES OF ERRORS

Default. The following sections are informative. 

APPLICATION USAGE

EXAMPLES

Open readfile as file descriptor 3 for reading: exec 3 readfile Open writefile as file descriptor 4 for writing: exec 4> writefile Make file descriptor 5 a copy of file descriptor 0: exec 5 Close file descriptor 3: exec 3 Cat the file maggie by replacing the current shell with the cat utility: exec cat maggie 

RATIONALE

Most historical implementations were not conformant in that: foo=bar exec cmd did not pass foo to cmd.

FUTURE DIRECTIONS

SEE ALSO

Special Built-In Utilities 

© 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd.

Источник

Linux. Команда exec

Запуск сценария из командной строки приводит к запуску новой оболочки, которая и будет выполнять список команд, содержащихся в файле сценария. Другими словами, любой сценарий (или программа) запускается как дочерний процесс родительской командной оболочки. Однако, программа, выполняемая по команде exec , заменяет текущую программу, и поэтому в системе остается на один выполняемый процесс меньше.

Действие, когда какая либо команда или сама командная оболочка инициирует (порождает) новый подпроцесс, чтобы выполнить какую либо работу, называется ветвлением (forking) процесса. Новый процесс называется «дочерним» (или «потомком»), а породивший его процесс — «родительским» (или «предком»). В результате и потомок и предок продолжают исполняться одновременно — параллельно друг другу.

Пусть нам нужно настроить среду для выполнения определенной задачи, например, для работы с базой данных: заменить приглашение в переменной PS1 на DataBase , добавить в переменную PATH каталог bin базы данных, изменить переменную CDPATH (чтобы было удобнее использовать команду cd ) и т.п.

#!/bin/bash # # Установить и экспортировать переменные, связанные с базой данных # HOME=/usr/database BIN=$HOME/bin RPTS=$HOME/rpts DATA=$HOME/data PATH=$PATH:$BIN CDPATH=:$HOME:$RPTS PS1="DataBase: " export HOME BIN RPTS DATA CDPATH PS1 # запустить новую оболочку с замещением текущего сценария exec /bin/bash

С помощью команды exec можно переназначить стандартный ввод ( stdin ) и стандартный вывод ( stdout ). Например, переназначим стандартный ввод:

Любые последующие команды, читающие данные со стандартного ввода, будут читать их из файла inputFile.txt . Пример использования в сценарии:

Переадресация стандартного вывода выполняется аналогично:

$ exec > outputFile.txt # или exec 1> outputFile.txt

Следует, однако, иметь в виду, что в обоих примерах команда exec применялась не для запуска новой программы на выполнение, а лишь для переназначения стандартного ввода или вывода.

Чтобы переназначить стандартный ввод обратно на терминал, достаточно ввести команду:

Аналогичным образом переназначается и стандартный вывод:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

  • 1С:Предприятие (31)
  • API (29)
  • Bash (43)
  • CLI (99)
  • CMS (139)
  • CSS (50)
  • Frontend (75)
  • HTML (66)
  • JavaScript (150)
  • Laravel (72)
  • Linux (145)
  • MySQL (76)
  • PHP (125)
  • React.js (66)
  • SSH (27)
  • Ubuntu (68)
  • Web-разработка (509)
  • WordPress (73)
  • Yii2 (69)
  • БазаДанных (95)
  • Битрикс (66)
  • Блог (29)
  • Верстка (43)
  • ИнтернетМагаз… (84)
  • КаталогТоваров (87)
  • Класс (30)
  • Клиент (27)
  • Ключ (28)
  • Команда (68)
  • Компонент (60)
  • Конфигурация (61)
  • Корзина (32)
  • ЛокальнаяСеть (28)
  • Модуль (34)
  • Навигация (31)
  • Настройка (139)
  • ПанельУправле… (29)
  • Плагин (33)
  • Пользователь (26)
  • Практика (99)
  • Сервер (74)
  • Событие (27)
  • Теория (105)
  • Установка (66)
  • Файл (47)
  • Форма (58)
  • Фреймворк (192)
  • Функция (36)
  • ШаблонСайта (68)

Источник

Linux exec Command With Examples

The Linux exec command executes a Shell command without creating a new process. Instead, it replaces the currently open Shell operation. Depending on the command usage, exec has different behaviors and use cases.

This article demonstrates how to use the exec command in Linux.

Linux exec Command With Examples

  • Access to the command line/terminal as sudo.
  • Basic understanding of Linux terminal commands (use our Linux commands cheat sheet).
  • A Linux text editor such as nano.

Linux exec Command Syntax

The exec command syntax is:

exec [options] [command [arguments]] [redirection]

The command behaves differently depending on the number of arguments:

  • If an argument is present, the exec command replaces the current shell with the executed program. In a Bash script, any commands after do not get executed.
  • If no command argument is present, all redirections occur in the current shell.

The exec command never returns to the original process unless there’s an error or the command runs in a subshell.

Linux exec Command Options

Below is a brief explanation of all exec options:

Option Description
-c Executes the command in an empty environment.
-l Passes a dash ( ) as the zeroth argument.
-a [name] Passes a [name] as the zeroth argument.

Continue reading to see how exec works through examples.

Linux exec Command Examples

The examples below demonstrate the behavior of the exec command in the terminal and through Bash scripts.

Basic Use (Process Replacement)

To see how exec works, do the following:

ps bash pid terminal output

The output shows the currently running Bash shell and the ps command. The Bash shell has a unique PID.

2. To confirm, check the current process ID with:

echo pid current process

The PID is the same as the output from the ps command, indicating this is the currently running Bash process.

3. Now, run exec and pass the sleep command for one hundred seconds:

The sleep command waits for 100 seconds.

4. In another terminal tab, list all currently running processes and grep the sleep command:

ps -ae grep sleep terminal output

The PID for the process is the same as the Bash shell PID, indicating the exec command replaced the Bash shell process.

The Bash session (terminal tab) closes when the one hundred seconds are complete and the process ends.

Replace Current Shell Session

Use the exec command to replace the current shell session:

1. Check the current shell PID:

2. Use exec to switch to the Bourne Shell:

exec sh current pid terminal output

3. In another tab, check the PID for the Bourne Shell process:

ps -ae grep sh terminal output

Note: The \b in grep is Regex for matching word boundary, allowing an exact match of sh in the output. Learn more in our Grep Regex tutorial.

The command replaces the Bash process. Exiting the Bourne Shell exits the terminal session completely.

Program Calls With exec in Bash Scripts

To see how exec works in Bash scripts, do the following:

1. Open a text editor, such as Nano, and create a script file:

2. Paste the following code:

#!/bin/bash while true do echo "1. Update " echo "2. Upgrade " echo "3. Exit" read Input case "$Input" in 1) exec sudo apt update ;; 2) exec sudo apt upgrade ;; 3) break esac done

exec in bash script selection

The script does the following:

  • Line 3 creates an infinite while loop.
  • Lines 5-7 print the three possible options.
  • Line 8 reads the user’s input into the variable $Input .
  • Line 9 starts a case statement checking the user’s input.
  • Lines 10-11 execute the apt update or apt upgrade command in place of the current shell. When the update or upgrade process ends, the terminal session exits.
  • Line 12 uses the break statement to exit the infinite while loop and ends the script. The session returns to the current shell as usual.

3. Save the script and close Nano.

4. Run the Bash script in the current environment to see the results:

exec script running terminal output

Executing the script with the source command applies the script behavior to the current Bash shell. Use exec to run Bash scripts within other programs for a clean exit.

Logging Bash Scripts

The exec command finds use in manipulating file descriptors for error logging in Bash scripts. The default Linux file descriptors are:

Use the exec command and redirect the file descriptors to a file to create logs. To see how logging works, follow the steps below:

1. Create a sample Bash script:

2. Paste the code into the file:

#!/bin/bash # Create test.log file touch test.log # Save test.log to log_file variable log_file="test.log" # Redirect stdin to $log_file exec 1>>$log_file # Redirect stderr to the same place as stdin exec 2>&1 echo "This line is added to the log file" echo "And any other lines after" eho "This line has an error and is logged as stderr"

logging.sh script contents

The script redirects all command outputs and errors to the same file (test.log).

3. Save the script and close the text editor.

The script does not output any code. Instead, all the output logs to the test.log file.

6. Use the cat command to see the test.log file contents:

exec stdin and stderr logging terminal output

The log file contains all the standard outputs and error messages. Use exec to debug scripts and log inputs, outputs, or errors depending on the situation.

Run Scripts in a Clean Environment

The -c option for the exec command creates a clean environment. To demonstrate, do the following in the terminal:

1. Start a new Bash shell session:

2. Use the printenv command to print all the environment variables in the current Bash shell:

printenv bash shell terminal output

The command prints all the environment variables for the current Bash shell session.

3. Run the same command using exec with the -c flag:

exec -c printenv clean environment termianl output

The command printenv runs in a clean environment, and no variables output to the console. Use the -c option to run scripts or commands in clean environments.

exec With find Command

The find command in Linux has the exec command as an option to execute an action on discovered content. For example, the line below executes the chmod command on the find command results:

sudo find ~ -name "test.log" -exec chmod +x '<>' \;

find and exec command terminal output

The find command searches through the home directory (~) for the test.log file and executes the permission change.

After following the examples from this tutorial, you should know how to use the exec command effectively in Bash scripts.

Источник

Читайте также:  Закрыть окно терминала линукс
Оцените статью
Adblock
detector