public
Created

run script and cp stdin and stdout

  • Download Gist
example.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
echo x - ScriptRunner.java
cat >ScriptRunner.java <<'!Funky!Stuff!'
 
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
*
* @author Ted
*/
public class ScriptRunner {
 
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.err.println("Usage: ScriptRunner myscript parameter...");
}
ScriptRunner runner = new ScriptRunner();
runner.run(args);
}
 
public int run(String[] args) throws Exception {
 
Process child = new ProcessBuilder(args).redirectErrorStream(true).start();
//subprocess reads input from a pipe via the output stream returned by Process.getOutputStream()
Thread readIn=plugTogether(System.in, child.getOutputStream());
Thread writeOut=plugTogether(child.getInputStream(), System.out);
int returnValule = child.waitFor();
if (returnValule != 0) //failed
{
System.err.println("failed with exit value: " + returnValule);
}else{
System.out.println("Script successfully finished\n");
}
//stop the threads
writeOut.interrupt();
readIn.interrupt();
return returnValule;
}
 
private Thread plugTogether(InputStream fin, OutputStream fout) throws Exception {
Thread workThread = new CopyWorker(fin, fout);
workThread.start();
return workThread;
}
 
class CopyWorker extends Thread {
 
final InputStream in;
final OutputStream out;
 
public CopyWorker(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
 
public void run() {
Thread thisThread = Thread.currentThread();
int c;
try {
while (!thisThread.isInterrupted() && (c=in.read()) !=-1) {
out.write(c);
out.flush();
thisThread.sleep(2);
}
} catch (IOException ex) {
Logger.getLogger(ScriptRunner.class.getName()).log(Level.SEVERE, null, ex);
}catch (InterruptedException ex){
System.out.println("cancel thread");
}
}
}
}
!Funky!Stuff!
echo x - choice.sh
cat >choice.sh <<'!Funky!Stuff!'
echo "continue?"
choices="yes no"
select name in $choices
do
if [ "$name" = "yes" ]; then
echo "working .."
echo "continue?"
else
echo "exit."
break
fi
done
!Funky!Stuff!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.