Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a two part question. First, is there a method to run a script whenever another (particular) script runs?

Secondly, I have created a script which I am using to 'override' the package 'cd' script, however, I've done this using aliases, and I'm wondering if there is a better (more proper) way to do this, or for that matter if my method will cause any errors done the road.

Allow me to explain my script... whenever "cd" is asked to move to a non-existent directory, it would than give the user the option to relocate the the 'deepest' existent directory in the entered path. It would be easier with an example...

Say I entered:

cd /var/www/html/foo

and that /var/www/html/foo does not exist, but /var/www/html does. the user would than be asked if they would like to proceed to /var/www/html.

I was able to make this happen using an alias and the following script:

   #!/bin/bash
   cd $*
   <code to check if valid, et cetera>

However, this is done by using

   alias cd='cdImproved'

As such, I'm uncertain if I will run into any problems doing this done the road, or if there is a more 'proper' way of doing the same thing.

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

I'm assuming that this cd &* is a typo and you mean this: cd $*. Also, this should not have any spaces around the equal sign: alias cd='cdImproved'.

You can't cd in a script that you run normally and have the new directory be set for the current shell. You have to use an alias, a function or source the script.

You can certainly define your function or alias in a file and source that in each script that you want to have make use of it. That would be the way to go. Since cd is a shell builtin, you'd have to modify the shell or create a loadable builtin to change its behavior globally.

To use aliases inside a script you'll have to turn on that feature in the script:

shopt -s expand_aliases
share|improve this answer
    
yeah, both of those were mistakes were just typos. Fixed them. So if I understand what you're saying, what I'm doing is correct in terms of cd? set: alias cdImproved='cd' and than cdImproved would call cd? The final bit about using aliases inside a script wasn't one of my questions, but it's a good fact to know, so thank you! –  Wipqozn Feb 21 '11 at 19:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.