- What does an «exec» command do?
- 4 Answers 4
- Linux. Команда exec
- Linux exec Command With Examples
- Linux exec Command Syntax
- Linux exec Command Options
- Linux exec Command Examples
- Basic Use (Process Replacement)
- Replace Current Shell Session
- Program Calls With exec in Bash Scripts
- Logging Bash Scripts
- Run Scripts in a Clean Environment
- exec With find Command
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.
But actually your script uses exec in a special way which can be explained much more simply, I will write an answer.
4 Answers 4
exec [-cl] [-a name] [command [arguments]] If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what login(1) does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to the executed command. If command cannot be executed for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. In that case, it returns failure. An interactive shell returns failure if the file cannot be executed. If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1.
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
bash-3.2$ bash bash-3.2$ exec > file bash-3.2$ date bash-3.2$ exit bash-3.2$ cat file Thu 18 Sep 2014 23:56:25 CEST
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.
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 (143)
- MySQL (76)
- PHP (125)
- React.js (66)
- SSH (27)
- Ubuntu (66)
- Web-разработка (509)
- WordPress (73)
- Yii2 (69)
- БазаДанных (95)
- Битрикс (66)
- Блог (29)
- Верстка (43)
- ИнтернетМагаз… (84)
- КаталогТоваров (87)
- Класс (30)
- Клиент (27)
- Ключ (28)
- Команда (68)
- Компонент (60)
- Конфигурация (59)
- Корзина (32)
- ЛокальнаяСеть (28)
- Модуль (34)
- Навигация (31)
- Настройка (137)
- ПанельУправле… (29)
- Плагин (33)
- Пользователь (26)
- Практика (99)
- Сервер (74)
- Событие (27)
- Теория (104)
- Установка (65)
- Файл (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.
- 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:
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:
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:
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:
3. In another tab, check the PID for the Bourne Shell process:
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
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:
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"
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:
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:
The command prints all the environment variables for the current Bash shell session.
3. Run the same command using exec with the -c flag:
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 '<>' \;
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.