简体   繁体   English

在Shell和tcsh之间的脚本中更改Shell

[英]Change shell within a script between shell and tcsh

I have a situation where my default shell is set to sh or bash in the script. 我遇到的情况是在脚本中将默认shell设置为sh或bash。 I have to change my shell in order to execute certain commands in tcsh. 我必须更改外壳程序才能在tcsh中执行某些命令。 When I am doing this, I am not able to set the variables. 当我这样做时,我无法设置变量。

#!/bin/sh
Variables=/path/set

 tcsh
vendor_command.sh

ret=$?

if (ret!= 0)
exit "$ret"
else
echo "success"
fi

Is there a way to do this? 有没有办法做到这一点?

Answering the literal question: No, you cannot seamlessly switch between scripting languages, passing shell-local variables bidirectionally between them, without implementing that data-passing protocol yourself. 回答字面上的问题: 不,您不能在脚本语言之间无缝切换,无法在脚本语言之间双向传递外壳本地变量,而无需自己实现该数据传递协议。

You can embed a tcsh script in your POSIX sh script, as so: 可以将tcsh脚本嵌入POSIX sh脚本中,如下所示:

#!/bin/sh
# this is run with POSIX sh
export var1="tcsh can see this"
var2="tcsh cannot see this"

tcsh <<'EOF'
# this is run with tcsh
# exported variables (not shell-local variables!) from above are present
var3="calling shell cannot see this, even if exported"
EOF

# this is run in the original POSIX sh shell after tcsh has exited
# only variables set in the POSIX shell, not variables set by tcsh, are available

...however, when the tcsh interpreter exits, all its variables disappear with it. ...但是,当tcsh解释器退出时,其所有变量随之消失。 To pass state around otherwise, you'd need to either emit content on stdout and read or evaluate it; 要以其他方式传递状态,您需要在stdout上发出内容并对其进行读取或评估。 write contents to a file; 将内容写入文件; or otherwise explicitly implement some interface to pass data between the two scripts. 或者以其他方式显式实现一些接口,以在两个脚本之间传递数据。


All that said, your example is trivially rewritten with no need for tcsh at all: 综上所述,您的示例已被完全重写,完全不需要tcsh:

#!/bin/sh -a
# the -a above makes your variables automatically exported
# ...so that they can be seen by the vendor's script.

Variables=/path/set

# If vendor_command exits with a nonzero exit status, this
# ...makes the script exit with that same status.
vendor_command.sh || exit

echo "success"

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

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