Linux 在 Bash 中将文本文件作为命令运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9825495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:20:49  来源:igfitidea点击:

Run text file as commands in Bash

linuxbashubuntuterminalcommand

提问by Blainer

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.

如果我有一个文本文件,每行都有一个单独的命令,我将如何让终端将每一行作为命令运行?我只是不想一次复制和粘贴 1 行。它不必是一个文本文件......它可以是任何可以工作的文件。

example.txt:

example.txt

sudo command 1
sudo command 2
sudo command 3

采纳答案by Chaos

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

你可以用这些命令制作一个shell脚本,然后chmod +x <scriptname.sh>,然后运行它

./scriptname.sh

Its very simple to write a bash script

编写 bash 脚本非常简单

Mockup sh file:

样机sh文件:

#!/bin/sh
sudo command1
sudo command2 
.
.
.
sudo commandn

回答by kclair

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

您也可以使用 shell 运行它,例如:

bash example.txt

sh example.txt

回答by QuantumMechanic

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 sudoas a command. But it gives you an idea on how to start.

尽管如果命令有参数(即行中有空格),您可能需要稍微调整一下以保护空格,以便将整个字符串视为sudo命令。但它让你知道如何开始。

回答by David L.

Execute

执行

. example.txt

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

这正是您所要求的,无需在文件上设置可执行标志或运行额外的 bash 实例。

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

有关详细说明,请参见例如https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i