Ubuntu – how to source csh script from bash environment

bashcshsource

I am using bash shell but some of the scripts that I need to source are in csh format. Can somebody tell how I can source csh scripts from bash shell?

By sourcing I mean the sourced csh script should be able to set the environment variables. So, I want to do something like this in my ~/.bashrc:

source path/to/csh_script/script.cshrc

Best Answer

bash won't run all csh scripts perfectly. There may be some basic overlap, like very basic bash scripts will run in sh/dash, but if it fails to run in bash (test with bash [file] ) then it's a no-go. Either

  • modify them to run in bash, or
  • run them with csh, called from the bash script, as if you're running them in a terminal, having them return a result value or do whatever they're supposed to. This would not leave any variables or functions available to the main bash script, as you've commented, so you'll either

    • have them do whatever they're supposed to do to external files, or
    • return a single value/string, or maybe
    • treat them like another program and read multiple lines of output into your bash script.

If you're just looking to source variables, it's theoretically possible to go through the csh script line-by-line and adding just the variables into the current bash shell/script. Something similar to this:

while read line
do
[stuff with $line]
done < /path/to/[the csh script to add]

I don't know how all the variables are laid out in the scripts you're sourcing, so it's up to you to decide what the [stuff with $line] should be.

  • If they're like bash, then maybe just grep any lines that begin with spaces or characters, have a = with optionally more characters with no spaces, so:

    echo "$line" | grep '^\s*\S*=\S*'

  • or as above with anything after the = with:

    echo "$line" | grep '^\s*\S*=.*'

But I think csh variables all start with set / setenv, so could find set/setenv lines, then throw out the set/setenv. Try as a starter:

echo "$line" | grep '^\s*\S*set.*=.*'

Those're just quick sample grep / regex patterns, see this & that & others for more info.

Or, if it's only a few of them, go through them manually & paste all the variables into bash/sh compatible files you can then source in bash with no problems.