The Linux source command: run scripts in the current shell

What is the source command?

The commandsource(also represented by one point).) is a build-in of the Bash, Zsh and others shells that allows you to read and run the content of a script file within the same shell process. Unlike running a script with./script.shorbash script.sh, source does not create a subprocess; therefore, any variable, function or alias that the script defines is available in the current shell after the execution is completed.

Basic syntax

The simplest way is:

source nombre_del_script.sh

or, equivalent:

. nombre_del_script.sh

The point should be followed by a space before the file name. If the script is not in the current directory, a relative or absolute route can be indicated.

Why use source instead of running the script normally?

  • Peristence of variables:The variables defined within the script remain in the shell environment.
  • Functions and aliases:You can define functions that are then called directly from the command line.
  • Configuration Recharge:Files like.bashrc, .zshrcor.profileare recharged with source to apply changes without closing the terminal.
  • Debugging and testing:It allows to test code fragments in the same environment where other projects are worked.

Practical examples

1. Define and use a variable

We create a file calledconfig.shwith the following content:

# config.sh
MI_VAR='Hola desde source'
export OTRA_VAR=42

Then in the terminal:

source config.sh
echo $MI_VAR
echo $OTRA_VAR

The output shall be:

Hola desde source
42

2. Load Functions

Infunciones.sh:

saludar() {
  echo '¡Hola, '$1'!'
}

Then in the terminal:

source funciones.sh
saludar Mundo

Outcome:

¡Hola, Mundo!

3. Recharge shell configuration

If you edit.bashrcAnd you want to apply the changes:

source ~/.bashrc

Limitations and considerations

  • Source only works in shells that implement it as build-in (Bash, Zsh, Ksh, etc.). In minimum shells likedashmay not be available.
  • If the script contains commands that change the work directory (cd) or modify environment variables (export), these changes will affect the current shell, which may or may not be desired according to the case.
  • It is important to ensure that the script is reliable, as it sources it runs all its content with the same privileges as the current user.

Conclusion

The commandsourceis an essential tool for any Linux user who wants to maintain a dynamic and efficient working environment. It allows you to integrate configuration scripts, define reusable variables and functions, and recharge settings without leaving the current session. Dominating its use improves productivity and avoids unnecessary subprocess creation, making the shell more reactive and adaptable to your needs.

This work is under aCreative Commons License Attribution 4.0 International for Francesc Roig francesc @ vivaldi.net.

EnglishenEnglishEnglish