Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a csh script from a sh script

I was wondering if there is a way to source a csh script from a sh script. Below is an example of what is trying to be implemented:

script1.sh:

#!/bin/sh

source script2

script2:

#!/bin/csh -f

setenv TEST 1234
set path = /home/user/sandbox

When I run sh script1.sh, I get syntax errors generated from script2 (expected since we are using a different Shebang). Is there a way I can run script2 through script1?

like image 490
user3245776 Avatar asked Jan 28 '14 18:01

user3245776


4 Answers

Instead of source script2 run it as:

csh -f script2
like image 52
anubhava Avatar answered Oct 07 '22 19:10

anubhava


Since your use case depends on retaining environment variables set by the csh script, try adding this to the beginning of script1:

#!/bin/sh

if [ "$csh_executed" -ne 1 ]; then
    csh_executed=1 exec csh -c "source script2;
                                exec /bin/sh \"$0\" \"\$argv\"" "$@"
fi

# rest of script1

If the csh_executed variable is not set to 1 in the environment, run a csh script that sources script2 then executes an instance of sh, which will retain the changes to the environment made in script2. exec is used to avoid creating new processes for each shell instance, instead just "switching" from one shell to the next. Setting csh_executed in the environment of the csh command ensures that we don't get stuck in a loop when script1 is re-executed by the csh instance.


Unfortunately, there is one drawback that I don't think can be fixed, at least not with my limited knowledge of csh: the second invocation of script1 receives all the original arguments as a single string, rather than a sequence of distinct arguments.

like image 30
chepner Avatar answered Oct 07 '22 17:10

chepner


You don't want source there; it runs the given script inside your existing shell, without spawning a subprocess. Obviously, your sh process can't run something like that which isn't a sh script.

Just call the script directly, assuming it is executable:

script2
like image 45
Wooble Avatar answered Oct 07 '22 18:10

Wooble


The closest you can come to sourcing a script with a different executor than your original script is to use exec. exec will replace the running process space with the new process. Unlike source, however, when your exec-ed program ends, the entire process ends. So you can do this:

#!/bin/sh

exec /path/to/csh/script

but you can't do this:

#!/bin/sh

exec /path/to/csh/script
some-other-command

However, are you sure you really want to source the script? Maybe you just want to run it in a subprocess:

#!/bin/sh

csh -f /path/to/csh/script
some-other-command
like image 39
kojiro Avatar answered Oct 07 '22 18:10

kojiro