Run text file as commands in Bash

前端 未结 4 1574
滥情空心
滥情空心 2020-11-29 20:09

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 tim

相关标签:
4条回答
  • 2020-11-29 20:55

    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.

    0 讨论(0)
  • 2020-11-29 20:57

    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
    
    0 讨论(0)
  • 2020-11-29 20:58

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

    bash example.txt
    
    sh example.txt
    
    0 讨论(0)
  • 2020-11-29 21:05

    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

    0 讨论(0)
提交回复
热议问题