Question

I am writing a bash script (called gotodir.sh) and would like to change directories during the course of the script, depending on some variables, say cd /home/username/${FOO}/${BAR}.

Just running this as is doesn't work when the process exits, since the directory was changed in the subshell only.

My shell is tcsh. (Yeah, I know... not my choice here.) In my .cshrc file, I want to alias the keyword gotodir to gotodir.sh.

I have read that executing the script with a . or source prefix will cause the script to be run in the same shell (i.e. not a subshell).

I have tried putting the following in my .cshrc file:

alias gotodir . /home/username/bin/gotodir.sh

but this results in the error: /bin/.: Permission denied.

I have also tried using source instead of .

alias gotodir source /home/username/bin/gotodir.sh

but this results in the error: if: Expression Syntax.

How do I accomplish this using a bash script while running tcsh?

Was it helpful?

Solution

When you source a file from tcsh, it tcsh runs the commands. The #! is ignored as a comment because you're not running the file as a script, just reading commands from it as if they'd been entered at the shell prompt.

Your mission is doomed to failure. Only a tcsh cd command can change the current directory of a tcsh process.

But if you're willing to bend a little, you can write a script which runs as a separate process and outputs the name of the directory to cd to. Then set the alias like

alias gotodir 'cd `/blah/blah/thescript`'

Addendum

Adding an argument is possible, but tricky. Alias arguments look like history expansion, with !:1 expanding to the first argument. But quotes don't protect the ! character. You have to backslash it to prevent it being expanded during creation of the aliase, so it can do its work during the execution of the alias.

alias gotodir 'cd `/blah/blah/thescript \!:1`'

Additional quoting may be required to handle arguments and directories with spaces in them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top