繁体   English   中英

使用命令执行 shell 并返回

[英]Executing a shell with a command and returning

man bash seems to suggest that if I want to execute a command in a separate bash shell all I have to do is bash -c command :

   -c string If the -c option is present, then commands are read from string.

我想这样做是因为我需要在不同的环境中运行一些东西:

bash --rcfile ~/.bashrc.a -c mytest.a
bash --rcfile ~/.bashrc.b -c mytest.b

但是,这并没有按预期工作。 通过运行的bash shell 的数量可以看出,例如:

$ bash
$ ps
  PID TTY          TIME CMD
 7554 pts/0    00:00:00 bash
 7573 pts/0    00:00:00 ps
28616 pts/0    00:00:00 bash
$ exit
exit
$ ps
  PID TTY          TIME CMD
 7582 pts/0    00:00:00 ps
28616 pts/0    00:00:00 bash
$ bash -c ps
  PID TTY          TIME CMD
 7583 pts/0    00:00:00 ps
28616 pts/0    00:00:00 bash

应该如何修改对bash的调用,以便它将使用指定的 rc 启动一个新的 shell,在该 shell 中执行给定的命令,并根据修改后的环境退出?

它已经完全按照您想要的方式工作了。 缺少额外进程仅仅是由于 bash 的尾调用优化。

Bash 认识到,让 shell 实例的唯一工作是等待进程并退出是没有意义的。 相反,它将跳过分叉并直接exec该过程。 对于例如var=$(ps)来说,这是一个巨大的胜利,它将昂贵的分叉数量从 2 个减少到 1 个。

如果你给它额外的命令之后运行,这个优化不再有效,然后你会看到额外的过程:

$ bash -c 'ps'
  PID TTY          TIME CMD
 4531 pts/10   00:00:00 bash
 4540 pts/10   00:00:00 ps

$ bash -c 'ps; exit $?'
  PID TTY          TIME CMD
 4531 pts/10   00:00:00 bash
 4549 pts/10   00:00:00 bash
 4550 pts/10   00:00:00 ps

bash --rcfile ~/.bashrc.a mytest.a将已经在单独的进程中运行mytest.a -c用于直接指定 shell 命令,而不是运行脚本。

# NO!
bash for x in 1 2 3; do echo "$x"; done

# Yes.
bash -c 'for x in 1 2 3; do echo "$x"; done'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM