Run text file as commands in Bash

LinuxBashUbuntuTerminalCommand

Linux Problem Overview


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

Linux Solutions


Solution 1 - Linux

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

Solution 2 - Linux

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

bash example.txt

sh example.txt

Solution 3 - Linux

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

Solution 4 - Linux

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.

Solution 5 - Linux

cat /path/* | bash

OR

cat commands.txt | bash

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlainerView Question on Stackoverflow
Solution 1 - LinuxChaosView Answer on Stackoverflow
Solution 2 - LinuxkclairView Answer on Stackoverflow
Solution 3 - LinuxDavid L.View Answer on Stackoverflow
Solution 4 - LinuxQuantumMechanicView Answer on Stackoverflow
Solution 5 - LinuxOleg NeumyvakinView Answer on Stackoverflow