85

If I have a text file with a separate command on each line how would I make terminal run each line as a command? I just don't want to have to copy and paste 1 line at a time. It doesn't HAVE to be a text file... It can be any kind of file that will work.

example.txt:

sudo command 1
sudo command 2
sudo command 3
jww
  • 97,681
  • 90
  • 411
  • 885
Blainer
  • 2,552
  • 10
  • 32
  • 39

5 Answers5

107

you can make a shell script with those commands, and then chmod +x <scriptname.sh>, and then just run it by

./scriptname.sh

Its very simple to write a bash script

Mockup sh file:

#!/bin/sh
sudo command1
sudo command2 
.
.
.
sudo commandn
mido
  • 24,198
  • 15
  • 92
  • 117
Chaos
  • 11,213
  • 14
  • 42
  • 69
  • In linux extensions are not mandatory (you can even create a file with no extensions). It works even if extension is .txt – Manlio Mar 22 '12 at 15:37
  • Yes, but you should have this "#!/bin/sh" at the head of your file so that the kernel knows that its a shell script – Chaos Mar 22 '12 at 15:38
  • 2
    You do NOT! need to edit the file, nor do you need `#!/bin/sh` at the top of the file! You just need to do what `kclair` sez to do: `sh your_file_here_and_it_can_have_any_random_filename`. – aqn Mar 22 '12 at 20:01
  • You don't have to change the extension, nor add shebang at the top. If you make it executable `chmod +x example.txt` the shell executes a command equivalent to having a shell invoked with the pathname as its first operand. – Diego Torres Milano Dec 30 '20 at 18:02
90

You can also just run it with a shell, for example:

bash example.txt

sh example.txt
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
kclair
  • 2,124
  • 1
  • 14
  • 18
34

Execute

. example.txt

That does exactly what you ask for, without setting an executable flag on the file or running an extra bash instance.

For a detailed explanation see e.g. https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i

David L.
  • 3,149
  • 2
  • 26
  • 28
9

You can use something like this:

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

Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo as a command. But it gives you an idea on how to start.

QuantumMechanic
  • 13,795
  • 4
  • 45
  • 66
  • 4
    This is terrible advice if `foo.txt` contains more than one token on any line. You're much better off with `sudo -s – tripleee Jun 13 '18 at 05:37
5
cat /path/* | bash

OR

cat commands.txt | bash
Oleg Neumyvakin
  • 9,706
  • 3
  • 58
  • 62