man bash
nói:
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.
Hai dòng cuối cùng là điều quan trọng: Nếu bạn tự chạy exec
, không có lệnh, nó sẽ đơn giản làm cho các chuyển hướng áp dụng cho trình bao hiện tại. Bạn có thể biết rằng khi bạn chạy command > file
, đầu ra của command
được ghi file
thay vì vào thiết bị đầu cuối của bạn (điều này được gọi là chuyển hướng ). Nếu bạn chạy exec > file
thay thế, thì chuyển hướng áp dụng cho toàn bộ shell: Bất kỳ đầu ra nào được tạo bởi shell được ghi file
thay vì cho thiết bị đầu cuối của bạn. Ví dụ ở đây
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
Lần đầu tiên tôi bắt đầu một bash
vỏ mới . Sau đó, trong shell mới này tôi chạy exec > file
, để tất cả đầu ra được chuyển hướng đến file
. Thật vậy, sau đó tôi chạy date
nhưng tôi không nhận được đầu ra, vì đầu ra được chuyển hướng đến file
. Sau đó, tôi thoát khỏi shell của mình (để chuyển hướng không còn áp dụng nữa) và tôi thấy rằng file
thực sự có chứa đầu ra của date
lệnh tôi đã chạy trước đó.