home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 44.22 Finding a Program Name; Multiple Program Names Chapter 44
Shell Programming for the Uninitiated
Next: 45. Shell Programming for the Initiated
 

44.23 Reading Files with the . and source Commands

As article 6.2 explains, UNIX programs can never, ever modify the environment of their parents. A program can only modify the environment that later will be passed to its children. This is a common mistake that many new UNIX users make: they try to write a program that changes a directory (or does something else involving an environment variable) and try to figure out why it doesn't work. You can't do this. If you write a program that executes the cd command, that cd will be effective within your program - but when the program finishes, you'll be back in your original (parent) shell.

One workaround is to "source" the shell script file (for csh and bash ) or run it as a "dot" script ( sh , ksh and bash too). For example, if the file named change-my-directory contains:

cd /somewhere/else

you could use the following commands to change the current directory of the current shell:

% 

source change-my-directory


$ 

. change-my-directory

The source and . commands read a script file into the current shell instead of starting a child shell. These commands only work for shell script files (files containing command lines as you'd type them at a shell prompt). You can't use source or . to read a binary (directly executable) file into the shell.

If your shell doesn't have shell functions ( 10.9 ) , you can simulate them ( 10.10 ) with the . command. It acts a lot like a subroutine or function in a programming language.

- ML , JP


Previous: 44.22 Finding a Program Name; Multiple Program Names UNIX Power Tools Next: 45. Shell Programming for the Initiated
44.22 Finding a Program Name; Multiple Program Names Book Index 45. Shell Programming for the Initiated

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System