What are `source` command examples?

Here are some practical examples of using the source command in a Linux shell:

1. Sourcing the .bashrc File

After making changes to your .bashrc file (such as adding aliases or environment variables), you can apply those changes without restarting the terminal.

source ~/.bashrc

or using the shorthand:

. ~/.bashrc

2. Sourcing a Custom Script

If you have a custom script that sets up your environment or defines functions, you can source it to make those functions available in your current shell session.

Example: Suppose you have a script named my_setup.sh:

# my_setup.sh
export MY_VAR="Hello, World!"
alias greet='echo $MY_VAR'

You can source this script:

source ~/my_setup.sh

Now, you can use the greet alias in your terminal:

greet  # Outputs: Hello, World!

3. Sourcing a Profile File

If you want to apply changes made to your .bash_profile or .profile file, you can source it similarly.

source ~/.bash_profile

or

. ~/.profile

4. Sourcing Multiple Files

You can source multiple files in sequence if needed. For example:

source ~/.bashrc
source ~/.bash_aliases

5. Sourcing a Script with Arguments

While the source command itself does not pass arguments to the script, you can set environment variables before sourcing if needed.

Example:

export MY_ENV_VAR="Some Value"
source ~/my_script.sh

Summary

  • Use source filename or . filename to execute commands from a file in the current shell session.
  • Common use cases include applying changes from .bashrc, .bash_profile, or custom scripts.
  • Sourcing allows you to make functions, aliases, and environment variables available immediately without restarting the terminal.

If you have any further questions or need additional assistance, feel free to ask!

0 Comments

no data
Be the first to share your comment!