使用命令执行外壳并返回

时间:2019-10-02 17:58:32

标签: bash

man bash似乎表明,如果我想在单独的bash shell中执行命令,我要做的就是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中执行给定的命令(根据rc修改了env),然后返回?

2 个答案:

答案 0 :(得分:2)

它已经完全按照您想要的方式工作。缺少额外流程的原因仅仅是bash的尾部调用优化。

Bash认识到,拥有一个shell实例毫无意义,它的唯一工作就是等待进程并退出。相反,它将跳过分支并直接root@server# apt-cache show tpm2-tools Package: tpm2-tools Status: install ok installed Priority: optional Section: utils Installed-Size: 1524 Maintainer: Mathieu Trudel-Lapierre <mathieu.trudel-lapierre@canonical.com> Architecture: amd64 Version: 3.1.3-2 Depends: libc6 (>= 2.22), libcurl3-gnutls (>= 7.16.2), libssl1.1 (>= 1.1.0), libtss2-esys0 Description-en: TPM 2.0 utilities This package contains a set of tools to use with TPM 2.0 chips, for common tasks and features provided by the hardware; such as for doing basic key management, attestation, encryption and signing. Description-md5: 7dab290b7414623bbe70b4f8bc047903 Homepage: https://github.com/01org/tpm2.0-tools Package: tpm2-tools Priority: optional Section: universe/utils Installed-Size: 964 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Architecture: amd64 Version: 1.0.0+20160226.64b3334-0ubuntu2 Depends: libc6 (>= 2.14), libcurl3 (>= 7.16.2), libssl1.0.0 (>= 1.0.0), libtss2-0, libtss2-utils Filename: pool/universe/t/tpm2-tools/tpm2-tools_1.0.0+20160226.64b3334-0ubuntu2_amd64.deb Size: 90006 MD5sum: 2a5dd741bab5ba886508b87559d1151d SHA1: 65c4f508b8643d808eb28e481dc660a68a0aba3d SHA256: a8127c59b2ac7520f8f8993e9849f9dcc46486bced2f4b54c7fef56ac8e3b59e Description-en: TPM 2.0 utilities This package contains a set of tools to use with TPM 2.0 chips, for common tasks and features provided by the hardware; such as for doing basic key management, attestation, encryption and signing. Description-md5: 7dab290b7414623bbe70b4f8bc047903 Homepage: https://github.com/01org/tpm2.0-tools Bugs: https://bugs.launchpad.net/ubuntu/+filebug Origin: Ubuntu 进行该过程。例如,这是一个巨大的胜利。 var groups = client.Users[servicePrincipalId].GetMemberGroups(true).Request().PostAsync().Result; ,它将昂贵的叉子数量从2个减少到1个。

如果您给它附加的命令随后运行,则此优化不再有效,然后您将看到附加的过程:

var groups = client.DirectoryObjects[servicePrincipalId].GetMemberGroups(true).Request().PostAsync().Result;

答案 1 :(得分:1)

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

# 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'