簡體   English   中英

如何讓 bash 子shell繼承父級的設置選項?

[英]How to let bash subshell to inherit parent's set options?

假設我確實在腳本“a.sh”中set -x ,它會調用另一個腳本“b.sh”。

是否可以讓“b.sh”從“a.sh”繼承-x選項?

從父級導出SHELLOPTS ,從它調用的所有腳本都將繼承其標志。

$ cat ./foo
#!/bin/bash -
export SHELLOPTS
set -x
./bar
$
$ cat ./bar
#!/bin/bash -
set -o | grep xtrace
$
$ ./foo
+ ./bar
+ set -o
+ grep xtrace
xtrace          on

由於-x不是由子 shell 繼承的,因此您需要更明確一些。 您可以測試-x何時與$-特殊參數一起使用。

if [[ $- = *x* ]]; then
    # Set the option, then *source* the script, in a subshell
    ( set -x; . b.sh )
else
    # Simply run the script; subshell automatically created.
    ./b.sh
fi

如果腳本 b腳本 a,它們將被合並到腳本 b 中。 這可能會或可能不會為您解決您的問題!

就像@devnull 說的那樣,您可以使用. 在您的腳本中操作。

在.sh

. SETVALUES

在 b.sh

. SETVALUES

在 SETVALUES

set -x

無論您在何處調用 SETVALUES,這些值都將在該子 shell 中設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM