The exec command in linux

Exec Command – Process Replacement & Redirection in Bash

The Linux exec command is a bash builtin and a very interesting utility. It is not something most people who are new to Linux know. Most seasoned admins understand it but only use it occasionally. If you are a developer, programmer or DevOp engineer it is probably something you use more often. Lets take a deep dive into the builtin exec command, what it does and how to use it.

Table of Contents

Basics of the Parent / Child Process

In order to understand the exec command, you need a fundamental understanding of how shells create (fork) processes. When you open a terminal window a program is started, in my case gnome-terminal-server. That program creates a new “bash” process and gives you a command prompt. Most commands entered in the terminal window create a new child process.

Below is an example. I opened a terminal window which started the gnome-terminal-server. The Gnome terminal process created a bash process and gave me a prompt. Below you will see the PID (Process ID) of the Gnome Terminal is 14684. If you look closely as the bash process you will see it’s PPID (Parent Process ID) is the same. This means that it is a child process of the gnome-terminal-server.

Screenshot 1

Every time you run a command in a terminal, it creates (forks) a child process and runs the supplied command.

In the next example, I opened a second terminal window. I then ran the tail command. Bash creates a child process to run the tail command. We can prove this happened by once again looking at the process ID and Parent Process ID. In the screenshot below you can see the parent process for the tail command is the process ID of the original bash terminal.

Screenshot 2

That is a very basic example of how shells create child processes to execute commands. I will leave links to more information about child processes and sub-shells in the resources section at the end of this article. Now, on to the main event, the exec command.

What the Exec Command Does

In it’s most basic function the exec command changes the default behavior of creating a sub-shell to run a command. If you run exec followed by a command, that command will REPLACE the original process, it will NOT create a sub-shell.

An additional feature of the exec command, is redirection and manipulation of file descriptors. Explaining redirection and file descriptors is outside the scope of this tutorial. If these are new to you please read “Linux IO, Standard Streams and Redirection” to get acquainted with these terms and functions.

In the following sections we will expand on both of these functions and try to demonstrate how to use them.

How to Use the Exec Command with Examples

Let’s look at some examples of how to use the exec command and it’s options.

Basic Exec Command Usage – Replacement of Process

If you call exec and supply a command without any options, it simply replaces the shell with command.

Let’s run an experiment. First, I ran the ps command to find the process id of my second terminal window. In this case it was 17524. I then ran “exec tail” in that second terminal and checked the ps command again. If you look at the screenshot below, you will see the tail process replaced the bash process (same process ID).

Читайте также:  Как увеличить громкость выше максимума windows

Screenshot 3

Since the tail command replaced the bash shell process, the shell will close when the tail command terminates.

Exec Command Options

If the -l option is supplied, exec adds a dash at the beginning of the first (zeroth) argument given. So if we ran the following command:

It would produce the following output in the process list. Notice the highlighted dash in the CMD column.

The -c option causes the supplied command to run with a empty environment. Environmental variables like PATH, are cleared before the command it run. Let’s try an experiment. We know that the printenv command prints all the settings for a users environment. So here we will open a new bash process, run the printenv command to show we have some variables set. We will then run printenv again but this time with the exec -c option.

In the example above you can see that an empty environment is used when using exec with the -c option. This is why there was no output to the printenv command when ran with exec.

The last option, -a [name], will pass name as the first argument to command. The command will still run as expected, but the name of the process will change. In this next example we opened a second terminal and ran the following command:

Here is the process list showing the results of the above command:

Screenshot 5

As you can see, exec passed PUTORIUS as first argument to command, therefore it shows in the process list with that name.

Using the Exec Command for Redirection & File Descriptor Manipulation

The exec command is often used for redirection. When a file descriptor is redirected with exec it affects the current shell. It will exist for the life of the shell or until it is explicitly stopped.

If no command is specified, redirections may be used to affect the current shell environment.

Here are some examples of how to use exec for redirection and manipulating file descriptors. As we stated above, a deep dive into redirection and file descriptors is outside the scope of this tutorial. Please read “Linux IO, Standard Streams and Redirection” for a good primer and see the resources section for more information.

Redirect all standard output (STDOUT) to a file:

In the example animation below, we use exec to redirect all standard output to a file. We then enter some commands that should generate some output. We then use exec to redirect STDOUT to the /dev/tty to restore standard output to the terminal. This effectively stops the redirection. Using the cat command we can see that the file contains all the redirected output.

Open a file as file descriptor 6 for writing:

Open file as file descriptor 8 for reading:

Copy file descriptor 5 to file descriptor 7:

Close file descriptor 8:

Conclusion

In this article we covered the basics of the exec command. We discussed how to use it for process replacement, redirection and file descriptor manipulation.

In the past I have seen exec used in some interesting ways. It is often used as a wrapper script for starting other binaries. Using process replacement you can call a binary and when it takes over there is no trace of the original wrapper script in the process table or memory. I have also seen many System Administrators use exec when transferring work from one script to another. If you call a script inside of another script the original process stays open as a parent. You can use exec to replace that original script.

I am sure there are people out there using exec in some interesting ways. I would love to hear your experiences with exec. Please feel free to leave a comment below with anything on your mind.

Источник

команда exec в Linux с примерами

Команда exec в Linux используется для выполнения команды из самого bash. Эта команда не создает новый процесс, она просто заменяет bash командой, которая должна быть выполнена. Если команда exec успешна, она не возвращается к вызывающему процессу.

Читайте также:  Свойства устройства windows 10

Синтаксис:

Параметры:

  • c: используется для выполнения команды с пустой средой.
  • имя: используется для передачи имени в качестве нулевого аргумента команды.
  • l: используется для передачи тире в качестве нулевого аргумента команды.

Примечание: команда exec не создает новый процесс. Когда мы запускаем команду exec из терминала, текущий процесс терминала заменяется командой, предоставленной в качестве аргумента для команды exec.

Команда exec может использоваться в двух режимах:

    Exec с командой в качестве аргумента: В первом режиме exec пытается выполнить ее как команду, передавая оставшиеся аргументы, если таковые имеются, этой команде и управляя перенаправлениями, если они есть.

Пример 1:

Пример 2:

Команда exec ищет путь, указанный в переменной $ PATH, чтобы найти команду для выполнения. Если команда не найдена, команда exec, а также оболочка завершается с ошибкой.

Exec без команды: если команда не указана, перенаправления могут использоваться для изменения текущей среды оболочки. Это полезно, так как позволяет нам изменять файловые дескрипторы оболочки по нашему желанию. Процесс продолжается даже после выполнения команды exec, в отличие от предыдущего случая, но теперь стандартный ввод, вывод и ошибка изменяются в соответствии с перенаправлениями.

Пример:

Здесь команда exec изменяет стандарт из оболочки на файл tmp, и поэтому все команды, выполняемые после команды exec, записывают свои результаты в этот файл. Это один из самых распространенных способов использования exec без каких-либо команд.

Источник

Команда exec

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

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

Общая форма команды exec :

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

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

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

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

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

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

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

Источник

exec command in Linux with examples

exec command in Linux is used to execute a command from the bash itself. This command does not create a new process it just replaces the bash with the command to be executed. If the exec command is successful, it does not return to the calling process.

Syntax:

Options:

  • c: It is used to execute the command with empty environment.
  • a name: Used to pass a name as the zeroth argument of the command.
  • l: Used to pass dash as the zeroth argument of the command.

Note: exec command does not create a new process. When we run the exec command from the terminal, the ongoing terminal process is replaced by the command that is provided as the argument for the exec command.

The exec command can be used in two modes:

Example 1:

Example 2:

The exec command searches the path mentioned in the $PATH variable to find a command to be executed. If the command is not found the exec command as well as the shell exits in an error.
Exec without a command: If no command is supplied, the redirections can be used to modify the current shell environment. This is useful as it allows us to change the file descriptors of the shell as per our desire. The process continues even after the exec command unlike the previous case but now the standard input, output, and error are modified according to the redirections.

Читайте также:  Usb audio card linux

Example:

Here the exec command changes the standard out of the shell to the tmp file and so all the commands executed after the exec command write their results in that file. This is one of the most common ways of using exec without any commands.

Источник

What does an «exec» command do?

I don’t understand the bash command exec . I have seen it used inside scripts to redirect all output to a file (as seen in this). But I don’t understand how it works or what it does in general. I have read the man pages but I don’t understand them.

4 Answers 4

The last two lines are what is important: If you run exec by itself, without a command, it will simply make the redirections apply to the current shell. You probably know that when you run command > file , the output of command is written to file instead of to your terminal (this is called a redirection). If you run exec > file instead, then the redirection applies to the entire shell: Any output produced by the shell is written to file instead of to your terminal. For example here

I first start a new bash shell. Then, in this new shell I run exec > file , so that all output is redirected to file . Indeed, after that I run date but I get no output, because the output is redirected to file . Then I exit my shell (so that the redirection no longer applies) and I see that file indeed contains the output of the date command I ran earlier.

/.vnc/xstartup script which vncserver uses to configure a VNC server process and then exec gnome-session or exec startkde and so on.

exec is a command with two very distinct behaviors, depending on whether at least one argument is used with it, or no argument is used at all.

If at least one argument is passed, the first one is taken as a command name and exec try to execute it as a command passing the remaining arguments, if any, to that command and managing the redirections, if any.

If the command passed as first argument doesn’t exist, the current shell, not only the exec command, exits in error, unless the shell is interactive or the bash option execfail is set ( shopt -s execfail ). See also https://superuser.com/questions/992204/why-does-exec-non-existent-file-exits-the-shell-when-in-a-script-that-is-sourc

If the command exists and is executable, it replaces the current shell. That means that if exec appears in a script, the instructions following the exec call will never be executed (unless exec is itself in a subshell). A successful exec never returns. Shell traps like «EXIT» won’t get triggered either.

If no argument is passed, exec is only used to redefine the current shell file descriptors. The shell continue after the exec , unlike with the previous case, but the standard input, output, error or whatever file descriptor has been redirected take effect.

If some of the redirections uses /dev/null , any input from it will return EOF and any output to it will be discarded.

You can close file descriptors by using — as source or destination, e.g. exec . Subsequent read or writes will then fail.

Here are two examples:

This script will output «foo» as the cat command, instead of waiting for user input as it would have done in the usual case will take its input from the /tmp/bar file which contains foo.

This script will display 4 (the number of bytes in /tmp/bar) and immediately ends. The cat command won’t be executed.

Источник

Оцените статью