首页 > 解决方案 > 使用输入从文件运行 bash 脚本

问题描述

我想制作一个简单的 bash 脚本,该脚本使用命令对文件进行 for 循环并执行这些命令,并在发生错误时完成。我有这样的东西

#!/bin/bash
while IFS= read -r line; do
    echo $line
    output=$(eval $line)
    if [ $? -eq 0 ]
    then
        echo ok
    else
        echo $output
        break
    fi
    echo
done < summary.txt

问题是我要创建的第一个命令是 sudo 命令,所以我必须输入密码。我试着把它放在命令中

sudo -S <<< password <<< Y command

没有运气。我已经检查过,如果我直接放它而不必阅读它(而不是把它作为一个字符串),它是否有效。问题是如果没有循环,程序会很长,没有多大意义。

谢谢

标签: bash

解决方案


echo <password> | sudo -S < your command>

man sudo

   -S, --stdin
                 Write the prompt to the standard error and read the password from the standard input instead of using the terminal
                 device.  The password must be followed by a newline character.


推荐阅读