5

My question is:
why if I run some file with name aliases for example with content such as:

alias lsa="ls -a" 

directly:

$ ./aliases

it don't create the alias (may be only in script context).
But if I run it with command "source":

$ source aliases

it do the work? I mean after execution the alias "lsa" existing in context of command shell?
"man source" give: "No manual entry for source", and in google I just found that it runs Tcl, but why Tcl influence shell context and bush not?

2 Answers 2

7

Basically because when you run ./aliases, it creates a process in which your aliases exist but ends up immediately after, whereas when you source it, it applies to your current bash process.

To get help on source, you need to read the man bash. To save you the trouble:

source filename [arguments]
    Read and execute commands from filename in the current shell environment
    and return the exit status of the last command executed from filename.
    If filename does not contain a slash, file names in PATH are used to find
    the directory containing filename. The file searched for in PATH need not
    be executable. When bash is not in posix mode, the current directory is
    searched if no file is found in PATH. If the sourcepath option to the shopt
    builtin command is turned off, the PATH is not searched. If any arguments
    are supplied, they become the positional parameters when filename is
    executed. Otherwise the positional parameters are unchanged. The return
    status is the status of the last command exited within the script (0 if
    no commands are executed), and false if filename is not found or cannot
    be read.
1
5

When you run it as an executable script, the shell forks a copy of itself as a child process to run the script. This means that any changes to the aliases:

  • Will only be seen by that child.
  • Are lost as soon as the child exits.

By contrast, when you source the script:

  • It is run in the same process (as if you'd simply typed in its contents)
  • Changes to the aliases are retained.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .