Authors Top

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

In this tutorial, we’re going to take a look at how we can run our bash commands that are in a txt file, in the current shell.

2. Using bash

Let’s consider we have a file called sample.txt, which includes one echo command and a variable set:

$ cat sample.txt
echo "Hello World!"
var="variable is set"

We can run our file by using the bash command:

$ bash sample.txt
Hello World!

bash reads the file content and executes it in the current shell. So, we have access to all defined variables in the file:

$ echo $var
variable is set

Note that to run our file with bash, we don’t need to use chmod to gain execution permissions.

bash is one of the installed shells in our system. So, we can use other installed shells as well. To see a list of all available shells, we can take a look at the /etc/shells file:

$ cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/bash
/bin/rbash
/bin/dash

We can execute our file with any available shell. Let’s run our file using sh:

$ sh sample.txt
Hello World!

3. Using source

Let’s execute our file with the source command:

$ source sample.txt
Hello World!

source reads the file and executes the lines in the current shell. Therefore, if we set a variable it will remain set and if we have an exit command in our script, our session will exit:

$ echo $var 
variable is set

4. Using Dot

We can also use a dot to execute our file:

$ . sample.txt
Hello World!

The function of the dot is the same as the source command.

4.1. Dot Slash (./) Is Different

Running ./sample.txt will also print the Hello World! statement but the variable is not set:

$ ./sample.txt
Hello World!

Using ./(dot slash) will execute the file in a different shell and all the variables will be destroyed once that bash shell exits. So, the $var variable would be empty:

$ echo $var
 

Note that in this case, we need the execute permission to be able to run the file.

5. Conclusion

In this article, we’ve discussed the ways we can run our bash commands from a text file. We can use either installed shells, source, or dot.

Authors Bottom

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!