Open In App

eval vs source: For Executing Commands Within a Shell Script

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Source

The source' command in Bash is used to execute the content of another script within the current script. It’s also commonly represented by the .' (dot) operator. When you use source' or ‘.' followed by a script file, the commands and variables defined in that script are made available in the current script’s context. It’s typically used for sourcing configuration files or reusing functions and variables.
The source command is generally safer in terms of security because it doesn’t execute arbitrary code; it merely includes the content of the specified script. However, you should still be cautious when sourcing scripts to ensure that the sourced script doesn’t contain any 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: Create a “constants.sh” file on your system by opening a terminal using [Alt + Ctrl + T] or [Right Click -> Open in Terminal]

step_1

Fig 1.1: Terminal

Step 2: Create a “constants.sh” file and open it using the nano editor.

‘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_2

Fig 1.2: Opening constants.sh

Step 3: Write the following lines of script in the “constants.sh” file and save it using [Ctrl + S] and close the nano editor using [Ctrl + X]

constants.sh

# constants.sh
export PI="3.1415"
export A="Hello"


step_3

Fig 1.3: Content of constants.sh

Step 4: Create and open “source.sh” file using nano editor, write the following script. Save and close the nano editor with same instruction present in step 3.

source.sh

#!/bin/bash
#Source the constants file
source constants.sh
#Using echo to get values of constants.
echo "Value of PI: $PI"
echo "$A Geeks."



step_4

Fig 1.4: Opening source.sh file in nano editor

step_5

Fig 1.5: Content of source.sh file

Note: 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 “source.sh” file using the following command and check the output

$ 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.

step_6

Fig 1.6: Running source.sh

step_7

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.”

Eval

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: Opening a terminal using [Alt + Ctrl + T] or [Right Click -> Open in Terminal]

step_1

Fig 2.1: Terminal

Step 2: Create a “eval.sh” file and open it using the nano editor.

step_8

Fig 2.2: Opening eval.sh in nano editor

Step 3: Write the following lines of script in the “constants.sh” file and save it using [Ctrl + S] and close the nano editor using [Ctrl + X]

#!/bin/bash
# A dynamically generated command as a string
command="ls -l"
#use eval to execute the command
eval "$command"



  1. "!/ bin/bash": This is known as a “shebang” line, and it specifies that the script should be executed using the Bash shell.
  2. "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.
  3. "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.
step_9

Fig 2.3: Content of eval.sh

Step 4: Run the “eval.sh” file using the following command and check the output

$ bash eval.sh

step_11-min

Fig 2.5: Running eval.sh using bash command

When 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.

Frequently Asked Questions:

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.

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

.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads