Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Unix / scripting help

  1. Sep 18, 2009 #1
    hi! im trying to create a script that will run a program, enter inputs (this program requires some inputs for it to run), and then send the output to a file. im stuck on trying to get the script to enter in those inputs :( so far all i have is:

    ./program > file

    and unfortunately this doesnt work. ive tried like a thousand combinations that i thought would work but i cant figure it out. im pretty sure there is something wrong with the way im sending the outputs to the file, but i think i might be able to figure that out whereas i have no idea how to get the inputs inputted in correctly. im new to unix as you can tell. any help is appreciated!
    Last edited: Sep 19, 2009
  2. jcsd
  3. Sep 19, 2009 #2
    Your program could be buggy, you might have forgotten to do chmod +x on your script, you might have forgotten to put #!/bin/bash as the first line of the script (or #!/usr/bin/python or whatever your script interpreter is), you might not have permission to write to the file, or perhaps some other problem. Obviously you should have given more information than "it doesn't work."
  4. Sep 19, 2009 #3

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    That works quite nicely -- just not the way you think it should. The shell script command processor (which one? tcsh? bash? something else?) processes the first line by invoking ./program in a subprocess, with stdout redirected to file. What about stdin? Standard input to your shell script is presumably your terminal -- and you have said nothing to change that.

    You need to tell your shell script command processor that you want ./program run with standard input from something other than your terminal. There are many ways to do this. Two of them are to
    1. Write your data to a temporary file and run your program with this temporary file as input
    2. Run your program with data embedded in the script.

    1. Using a temporary file (assumes csh, tcsh, or something like that)
    Code (Text):
    set tempfile = `mktemp my_script.XXXXXX`
    echo "input 1" >> $tempfile
    echo "input 2" >> $tempfile
    echo "input 3" >> $tempfile
    ./program < $tempfile > file
    rm $tempfile

    2. Using a here document
    Code (Text):
    ./program > file <<EOF
    input 1
    input 2
    input 3
    What if you want to send the string EOF to your program? Simple: Use something other than EOF to demarcate the end of the here document.
    Code (Text):
    ./program > file <<DONE
    input 1
    input 2
    input 3
    The here document approach is nice and simple in this case.
  5. Sep 19, 2009 #4
    that worked perfectly, thanks!
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook