How to set an alias inside a bash shell script so that is it visible from the outside?

Viewed 62316

OSX: This works from the command line:

alias ruby="/opt/local/bin/ruby1.9"

but in side a shell script, it has no effect. I want to write a script that will switch between ruby 1.8 and ruby 1.9, so this needs to be a script - not in my profile.

It appears "source script.sh" works, but "./script.sh". Why is this? How can I replicate this in my script?

4 Answers

./script.sh will be executed in a sub-shell and the changes made apply only the to sub-shell. Once the command terminates, the sub-shell goes and so do the changes.

sourcing the file using . ./script.sh or source ./script.sh will read and execute commands from the file-name argument in the current shell context, that is when a script is run using source it runs within the existing shell, any variables created or modified by the script will remain available after the script completes.

You can write a function in your .profile to switch the aliases

function toggle-ruby() {
  if [ "$1" == "1.9" ]; then
    alias ruby=/opt/local/bin/ruby1.9
  else
    alias ruby=/opt/local/bin/ruby1.8
  fi
}

then run you can run:

toggle-ruby 1.9

or

toggle-ruby 1.8

to switch back and forth.

Related