简体   繁体   中英

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. I have to change my shell in order to execute certain commands in 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:

#!/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. To pass state around otherwise, you'd need to either emit content on stdout and read or evaluate it; 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:

#!/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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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