Run text file as commands in Bash

2019-01-07 06:58发布

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

3条回答
\"骚年 ilove
2楼-- · 2019-01-07 07:40

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
查看更多
\"骚年 ilove
3楼-- · 2019-01-07 07:53

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

bash example.txt

sh example.txt
查看更多
甜甜的少女心
4楼-- · 2019-01-07 08:01

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.

查看更多
登录 后发表回答