简体   繁体   English

如何在Bash子shell中执行shell脚本?

[英]How can I execute a shell-script in a Bash sub-shell?

I have a shell-function that executes a command within a sub-shell, after setting some environment variables, eg 我有一个shell函数,在设置一些环境变量之后,在子shell中执行命令,例如

$ with-env-overrides git status

It's implemented using eval in a sub-shell 它是在子shell中使用eval实现的

with-env-overrides() {
  (
    source $HOME/.env-overrides
    eval "$@"
  )
}

this means I can make use of aliases, and shell-functions, eg 这意味着我可以使用别名和shell函数,例如

$ with-env-overrides gs    

but unfortunately, eval gets confused when arguments contain spaces, or shell meta-characters, eg 但不幸的是,当参数包含空格或shell元字符时,eval会混淆

$ with-env-overrides grep "foo bar" /etc/passwd
grep: bar: No such file or directory

How can I achieve this without using eval , but without loosing the ability to use aliases etc? 如何在不使用eval情况下实现这一目标,但又不会失去使用别名等的能力?

You can do the same but without eval. 你可以做同样但没有 eval。

with-env-overrides() {
  (
    source $HOME/.env-overrides
    "$@"
  )
}

Example: 例:

$ cat ~/.env-overrides 
export A=1000
$ export | grep ^A=
$ with-env-overrides export | ^grep A=
declare -x A="1000"

As you can see, in the second case, you've got an environment with the A variable. 如您所见,在第二种情况下,您有一个带有A变量的环境。

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

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