eval vs source: For Executing Commands Within a Shell Script
Last Updated :
29 Apr, 2025
Shell scripting is a fundamental skill for anyone working with Unix-like operating systems, offering a powerful way to automate tasks and streamline workflows. Two key commands, "source" and "eval," play distinct roles in the realm of shell scripting. In this article, we delve into the core concepts of both commands, providing clear explanations, practical examples, and essential considerations for using them effectively. By understanding the nuances of "source" and "eval," you'll gain a deeper insight into how they can simplify your scripting tasks and navigate potential security concerns when handling untrusted input. Let's explore these essential tools for shell scripting and empower you to become a more proficient scripter.
What is the source Command?
The source command in Bash (also written as a single dot, .) lets you run the contents of another script inside your current script. This means any variables, functions, or settings defined in the source script become available in your current session. It’s like importing a set of tools or instructions into your workspace. You’ll often use source to load configuration files, environment variables, or reusable code, such as constants or functions.
The source command is generally safer than eval because it doesn’t execute random code it only includes the contents of a specific script file. However, you should still check that the sourced script is trustworthy to avoid running malicious code.
Example:
To begin, create a file named "constants.sh" where we will store constant values. In the following section, we will utilize the source command to incorporate this file.
Step 1: Open a Terminal
Opening a terminal using [Alt + Ctrl + T] or [Right Click -> Open in Terminal]
Fig 1.1: TerminalStep 2: Create a Configuration File
We’ll create a file called constants.sh to store some constant values. Open the terminal and type:
'nano': The 'nano'
command is a text editor for Unix-like operating systems, including Linux. It is designed to be easy to use and is often preferred by those who are new to the command line or need a simple text editor for quick edits. To open a file with nano
or create a new one, you can use the following command:
nano [filename]
Replace '[filename]'
with the name of the file you want to open or create. If the file does not exist, 'nano'
will create a new one with that name.
Once you're inside the 'nano'
text editor, you can use various keyboard shortcuts to perform actions like saving, quitting, searching, and more. Common shortcuts include:
- Ctrl + O: Save the current file.
- Ctrl + X: Exit '
nano'
. - Ctrl + G: Open the help menu, which shows other available commands.
- Ctrl + W: Search for text within the file.
- Ctrl + K: Cut (delete) the current line.
- Ctrl + U: Uncut (paste) the previously cut text.
You can find more commands and options in the help menu by pressing Ctrl + G.
Keep in mind that 'nano'
is a basic text editor, and if you need more advanced features, you might want to consider using other text editors like 'vim'
or 'emacs'
.
Step 3: Add Constants to constants.sh
In the nano editor, type the following:
# constants.sh
export PI="3.1415"
export A="Hello"
Fig 1.3: Content of constants.shSave the file by pressing Ctrl + O, then press Enter. Exit nano with Ctrl + X.
Step 4: Create a Script to Use source
Now, create a script called source.sh to use the source source` command. Type:
#!/bin/bash
#Source the constants file
source constants.sh
#Using echo to get values of constants.
echo "Value of PI: $PI"
echo "$A Geeks."
Fig 1.4: Opening source.sh file in nano editor
Fig 1.5: Content of source.sh fileNote: You can use any name for the script, I used "source.sh". Also here "source.sh" and "constants.sh" both are in the the same folder hence in execution of the the source command only file name is used but the syntax of the the source command is " source /path/to/your/file".
Step 5: Run the Script
Run the script by typing:
bash source.sh
The command "bash source.sh" is used to execute a Bash script called "source.sh." When you run this command, it will execute the commands specified in the "source.sh" script.
The "source" command within the script is used to include and execute the contents of another script or file. In this case,"source.sh" is meant to include and run the "constants.sh" file.
So, running "bash source.sh" will execute the commands within "source.sh," which, in turn, sources the "constants.sh" file and displays the values of variables.
Fig 1.6: Running source.sh
Fig 1.7: Output of source.sh
The provided Bash script sources to the file named "constants.sh" to access variables and then uses the 'echo'
command to display the values of those variables. This assumes that "constants.sh" contains variable definitions for PI
with the value of "3.14159" and A
with the value "42."
What is the eval Command?
The eval
command in Bash is used to evaluate and execute a string as a shell command. It takes a string as an argument and treats it as if it were a line of code in the script. The primary purpose of eval
is to dynamically generate and execute code. For example, you can build a command as a string and then use eval
to run it.
It's essential to exercise caution when using eval
because it can potentially introduce security risks, especially when dealing with untrusted or user-generated input. If not properly sanitized, it can be vulnerable to code injection attacks.
Example:
Step 1: Open a Terminal
Use [Alt + Ctrl + T] or right-click and select Open in Terminal.
Step 2: Create an eval Script
Create a file called eval.sh:
nano eval.sh
Fig 2.2: Opening eval.sh in nano editorStep 3: Add the Script
Type the following in the file in terminal and save (Ctrl + O, then Enter) and exit (Ctrl + X).
#!/bin/bash
# A dynamically generated command as a string
command="ls -l"
#use eval to execute the command
eval "$command"
"!/
bin/bash"
: This is known as a "shebang" line, and it specifies that the script should be executed using the Bash shell."ls -l
"
: In this line, a variable named command
is declared and assigned the value "ls -l." This value is a string, and it represents a shell command to list files and directories in long format."eval $command"
: The eval
command is used to evaluate and execute the contents of the command
variable. In this case, it takes the value of the command
variable, which is "ls -l," and treats it as a shell command. This results in the execution of the "ls -l" command as if it were directly entered into the shell.
Fig 2.3: Content of eval.shStep 4: Run the Script
Run it with:
bash eval.sh
Fig 2.5: Running eval.sh using bash commandWhen you run the command "bash eval.sh," it will execute the "ls -l" command using 'eval', and you'll see the output of the "ls -l" command, which will list the files and directories in the current directory in long format.
Comparison between Source and Eval:
Now that we have gained a solid understanding of both the 'source' and 'eval' commands, let's proceed with a comparative analysis of these two commands.
source | eval |
---|
The 'source' command is used to execute a script or file within a shell. | The 'Eval' command is used to evaluate and execute a string as a command. |
This command requires a file name as an argument. | This command requires a string that contains the command to be executed. |
Its scope affects the current shell session by modifying environment variables and functions. | Its scope affects the current shell session and is typically used dynamically executing commands. |
Typically used to load the environment variables, functions, constants, and aliases from a configuration file. | It is typically used to execute commands, which may potentially alter the environment. |
It is safer when sourcing trusted scripts. | It requires careful input validation to prevent code injections. |
Source command requires a separate script or file. | Eval doesn't require a separate script or file. |
Syntax flexibility is limited to sourced files or script. | Syntax flexibility is high as it allows dynamic generation of shell commands. |
Errors in the sourced script may affect the current shell. | Errors in the evaluated string may lead to unexpected results or failures. |
Conclusion
In summary, 'eval'
is used for executing dynamically generated code from a string, but it poses security risks when dealing with untrusted input. On the other hand, source
is used to include the content of other scripts and is generally safer, but you should be careful when sourcing external scripts
Question 2: What is the key difference in security considerations between using 'source' and 'eval' in Bash scripts, particularly when dealing with untrusted input?
Answer:
While both 'source' and 'eval' can be considered safe when employed with trusted input, it's important to note that 'eval' necessitates an additional layer of meticulous input validation to safeguard against potential code injections. Consequently, it tends to be riskier when handling untrusted input.
Question 2: Can I use 'source' to execute a single command?
Answer:
Indeed, it is possible to employ the 'source' command to execute a single command by encapsulating it within a file and then sourcing that file. Notably, there is no imposed limit on the file size that the 'source' command can handle and execute.
Question 3: What happens if there's an error in the sourced script or evaluated command?
Answer:
In either scenario, errors have the potential to impact the ongoing shell session. It is essential to exercise caution and perform thorough error handling and testing prior to executing scripts or files that incorporate these commands.
Similar Reads
Shell Scripting - Command Substitution
A shell is an interface that helps users to connect with the system. Using a shell is equivalent to indirectly communicating with the operating system. In Linux distributed systems, each time we use the terminal, we connect with a shell. The job of a shell is to analyze Unix commands or instructions
4 min read
source Command in Linux with Examples
If you're new to the world of Linux, you might have heard about commands that do various tasks, but some like the 'source' command might seem a bit confusing at first. Don't worry; let's break it down step by step. What is the Source Command?The source command in Linux is like a magic wand that lets
7 min read
scriptreplay command in Linux with Examples
scriptreplay command is used to replay a typescript/terminal_activity stored in the log file that was recorded by the script command. With the help of timing information, the log files are played and the outputs are generated in the terminal with the same speed the original script was recorded. The
3 min read
script command in Linux with Examples
The 'script' command in Linux is a versatile tool that allows you to record all terminal activities, including inputs and outputs, making it a valuable resource for developers, system administrators, educators, and anyone who needs to document terminal sessions. This command captures everything disp
6 min read
How to Execute Shell Commands in a Remote Machine in Python?
Running shell commands on a Remote machine is nothing but executing shell commands on another machine and as another user across a computer network. There will be a master machine from which command can be sent and one or more slave machines that execute the received commands. Getting Started We wil
3 min read
Shell Script to Perform Operations on a File
Most of the time, we use shell scripting to interact with the files. Shell scripting offers some operators as well as some commands to check and perform different properties and functionalities associated with the file. For our convenience, we create a file named 'geeks.txt' and another .sh file (or
5 min read
expect command in Linux with Examples
expect command or scripting language works with scripts that expect user inputs. It automates the task by providing inputs. // We can install expect command using following if not installed // On Ubuntu $sudo apt install expect // On Redhat based systems $ yum install expect First we write a script
2 min read
How to Execute a Python Script from the Django Shell?
The Django shell is an interactive development and scripting environment that aids us in working with our Django project while experiencing it as if it were deployed already. It is most commonly used when one has to debug, test, or carry out one-time operations that require interaction with the Djan
4 min read
Shell Script to Demonstrate Special Parameters With Example
Here, we are going to see what are the special Parameters of the shell script. Before that first, let's understand what is parameters in the shell. The parameter is the entity that stores the value. The variables are the parameters that are defined by the user to use in that specific shell script. A
5 min read
whereis command in Linux with Examples
'whereis' command is used to find the location of source/binary file of a command and manuals sections for a specified file in Linux system. If we compare 'whereis' command with 'find' command they will appear similar to each other as both can be used for the same purposes but 'whereis' command prod
4 min read