Coder Perfect

Run text file as commands in Bash


How would I make terminal run each line as a command if I have a text file with a different command on each line? I’d rather not have to copy and paste one line at a time. It isn’t necessary for it to be a text file… It doesn’t matter what kind of file it is; it will work.


sudo command 1
sudo command 2
sudo command 3

Asked by Blainer

Solution #1

You may use those instructions to create a shell script, then chmod +x> and run it.


Writing a bash script is fairly straightforward.

Mockup sh file:

sudo command1
sudo command2 
sudo commandn

Answered by Chaos

Solution #2

You can also use a shell to run it, for example:

bash example.txt

sh example.txt

Answered by kclair

Solution #3


. example.txt

That accomplishes your goal without requiring an extra bash instance or setting an executable flag on the file.

See, for example, for a full explanation.

Answered by David L.

Solution #4

You may use something similar to this:

for i in `cat foo.txt`
    sudo $i

If the commands involve parameters (i.e. there is whitespace in the lines), you may need to fiddle with it a little to protect the whitespace so that sudo recognizes the entire string as a command. However, it provides you an idea of where to begin.

Answered by QuantumMechanic

Solution #5

cat /path/* | bash


cat commands.txt | bash

Answered by Oleg Neumyvakin

Post is based on