dot-operator - Linux


Overview

The . command, also known as source in bash, is a built-in shell command used to execute commands from a file in the current shell session. This allows variables and functions defined in the file to remain in the current shell environment. It is primarily utilized for configuring shell environments or running shell scripts within the current context without spawning a new shell.

Syntax

The syntax of the . command is straightforward:

. filename [arguments]
  • filename: The path to the file containing the shell commands to be executed.
  • [arguments]: Optional arguments that can be passed to the script.

It’s important to ensure that the file is executable and contains valid shell script syntax.

Options/Flags

The . command does not have any options or flags. Its functionality is solely dependent on the content of the script it is asked to execute.

Examples

  1. Simple Source Usage:
    To source a script called script.sh that sets up environment variables:

    . ./script.sh
    
  2. Passing Arguments:
    If setup.sh takes an environment as an argument (like dev or prod):

    . setup.sh prod
    
  3. Sourcing a File from Another Directory:
    To source a file located in /etc/profile.d:

    . /etc/profile.d/custom.sh
    

Common Issues

  • Permission Denied: Ensure the file exists and the user has the appropriate permissions to read it.
    chmod +x filename
    
  • Command Not Found: This error typically indicates typos in the file path or filename.
  • Variables Not Set: If variables from a sourced file do not appear to affect the environment, check for subshell creation (e.g., using pipelines or parentheses).

Integration

The . command is commonly integrated with scripts that set up or modify the environment:

  • Scripted Setup:

    if [ -f ~/.bash_aliases ]; then
      . ~/.bash_aliases
    fi
    
  • Combining with Shell Scripts:
    A script may conditionally source other scripts based on user input or system status.

  • bash: Another shell where scripts and commands can be executed.
  • sh: The Bourne shell, often used interchangeably with bash in scripts.
  • chmod: Used to change the permissions of files to make them executable.

For further exploration, refer to the bash documentation or manpages like man bash for more on in-built commands like . (source).