Passing arguments to an interactive program non-interactively

前端 未结 6 920
一生所求
一生所求 2020-11-22 05:06

I have a bash script that employs the read command to read arguments to commands interactively, for example yes/no options. Is there a way to call this script i

相关标签:
6条回答
  • 2020-11-22 05:33

    You can put the data in a file and re-direct it like this:

    $ cat file.sh
    #!/bin/bash
    
    read x
    read y
    echo $x
    echo $y
    

    Data for the script:

    $ cat data.txt
    2
    3
    

    Executing the script:

    $ file.sh < data.txt
    2
    3
    
    0 讨论(0)
  • 2020-11-22 05:33

    anothe ralternative can be

    echo "something" | tee /path/to/file
    

    The tee command prints the input it receives to the screen and saves it to a file at the same time.

    0 讨论(0)
  • 2020-11-22 05:37

    You can also use printf to pipe the input to your script.

    var=val
    printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh
    
    0 讨论(0)
  • 2020-11-22 05:57

    For more complex tasks there is expect ( http://en.wikipedia.org/wiki/Expect ). It basically simulates a user, you can code a script how to react to specific program outputs and related stuff.

    This also works in cases like ssh that prohibits piping passwords to it.

    0 讨论(0)
  • 2020-11-22 05:57

    Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.

    yes | execute_command
    

    This will use yes as the answer to all yes/no prompts.

    0 讨论(0)
  • 2020-11-22 05:58

    Many ways

    pipe your input

    echo "yes
    no
    maybe" | your_program
    

    redirect from a file

    your_program < answers.txt
    

    use a here document (this can be very readable)

    your_program << ANSWERS
    yes
    no
    maybe
    ANSWERS
    

    use a here string

    your_program <<< $'yes\nno\nmaybe\n'
    
    0 讨论(0)
提交回复
热议问题