Dileep
Dileep

Reputation: 136

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?

Upvotes: 0

Views: 1637

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295373

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"

Upvotes: 3

Related Questions