Coder Perfect

Run text file as commands in Bash

Problem

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.

example.txt:

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 scriptname.sh> and run it.

./scriptname.sh

Writing a bash script is fairly straightforward.

Mockup sh file:

#!/bin/sh
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

Execute

. example.txt

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

See, for example, https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i for a full explanation.

Answered by David L.

Solution #4

You may use something similar to this:

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

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

OR

cat commands.txt | bash

Answered by Oleg Neumyvakin

Post is based on https://stackoverflow.com/questions/9825495/run-text-file-as-commands-in-bash