On ubuntu server, I can press up arrow to show the last command line which I used, and we can modify it by history -r , for example
$>history
... some command here
...
$> history -r hello.file
$>cat hello.file
aa
$>history
... some command here
...
aa
Of course, when I press up arrow at this time, the command line will give me "aa",
So that, I want some program to help me to do that
my Java sample code is
Runtime r = Runtime.getRuntime();
Process p = r.exec("/bin/bash history -r hello.file");
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = b.readLine()) != null) {
System.out.println(line);
}
b.close();
but it not work, and java didn't print any exception.
I also test by a simple bash file
my bash file:
#!/bin/bash
history -r hello.file
and my test follow is
$>history
... some command here
...
$>sh my_bash_file.sh
$>history
... some command here
...
it still not working...
How can I update the "history" by a program?
Is it impossible?
Related
I need to start a server using bash, so I had created an UNIX shell , but I am not able to execute it with Java from Eclipse.
I tried the following code which doesn't work :
Process proc = Runtime.getRuntime().exec(./startServer);
Here is content of the startServer file :
#!/bin/bash
cd /Users/sujitsoni/Documents/bet/client
npm start
You can try the following two options.
Option 1
Process proc = Runtime.getRuntime().exec("/bin/bash", "-c", "<Abosulte Path>/startServer");
Option 2
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "<Absolute Path>/startServer");
pb.directory(new File("<Absolute Path>"));
Process proc = pb.start();
A couple Of things can go wrong:
The path to the file you have given might be wrong for eclipse it can take relative path but from the command line, it will take the absolute path.
error=13, Permission denied - If the script file doesn't have required permissions. In your scenario, that might not the case as you are not getting any error.
At last, you are executing the script by java program so the output of your script will not be printed out. In your scenario, this might be the case. You need to capture the output of script from BufferedReade and print it. ( In your case server might have started but you are not seeing the logs/output of the script.
See the code sample below for printing output.
public static void main(String[] args) throws IOException, InterruptedException {
Process proc = Runtime.getRuntime().exec("./startServer");
proc.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output);
}
I am writing a Java program from which I am executing a shell script. The shell script is calling another shell script. I am trying to print output returned by child script to parent shell script.
Below is my code.
public class App
{
public static void main( String[] args ) throws IOException, InterruptedException
{
String command = new String("/home/Test.sh");
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(command);
process.waitFor(1, TimeUnit.MINUTES);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s);
}
Shell Script: Test.sh
#!/bin/bash
result=$( bash myscript.sh )
echo "$result"
myscript.sh
#!/bin/bash
echo "50"
I am getting empty output. I initial thought it might be because the Java process is not waiting for the shell script to finish. So added waitFor() but still no use. Can some one kindly help.
try this; this is not waiting problem.
#!/bin/bash
result=$( bash /home/myscript.sh ) # full path of myscript
echo "$result"
Also handle bash error as below;
public static void main(String[] args) throws IOException {
String command = new String("/tmp/1/Test.sh");
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s);
}
BufferedReader stdError = new BufferedReader(new
InputStreamReader(process.getErrorStream()));
System.out.println("Here is the standard error\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
adduser tests;
1-
myscript.sh:
#!/bin/bash
adduser test
echo "50"
java console output;
Script output: 50
Here is the standard error of the command (if any):
adduser: Only root may add a user or group to the system.
2-
myscript.sh:
#!/bin/bash
sudo adduser test
echo "50"
java console output;
Script output: 50
Here is the standard error of the command (if any):
sudo: no tty present and no askpass program specified
3-
myscript.sh:
#!/bin/bash
echo -e "YOURPASSWORD=\n" | sudo -S adduser -shell /bin/bash --home /home/test test
echo -e "YOURPASSWORD\n" | sudo deluser --remove-home test
echo "OK"
java console output;
Script output: Adding user `test' ...
Script output: Adding new group `test' (1002) ...
Script output: Adding new user `test' (1001) with group `test' ...
Script output: Creating home directory `/home/test' ...
Script output: Copying files from `/etc/skel' ...
Script output: Try again? [y/N] Changing the user information for test
Script output: Enter the new value, or press ENTER for the default
Script output: Full Name []: Room Number []: Work Phone []: Home Phone []: Other []: Is the information correct? [Y/n] Looking for files to backup/remove ...
Script output: Removing files ...
Script output: Removing user `test' ...
Script output: Warning: group `test' has no more members.
Script output: Done.
Script output: OK
Here is the standard error of the command (if any):
[sudo] password for ..: Enter new UNIX password: Retype new UNIX password: passwd: Authentication token manipulation error
passwd: password unchanged
Use of uninitialized value $answer in chop at /usr/sbin/adduser line 563.
Use of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 564.
Use of uninitialized value $answer in chop at /usr/sbin/adduser line 589.
Use of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 590.
This question already has answers here:
Runtime's exec() method is not redirecting the output
(2 answers)
Closed 7 years ago.
i'm trying to run shell command in linux via java. most of the commands work, but when i run the following command i get an execption, although it works in the shell:
String command = "cat b.jpg f1.zip > pic2.jpg";
String s = null;
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
i am getting the error in the console:
cat: >: No such file or directory
cat: pic2.jpg: No such file or directory
The problem is the redirection.
cat: >: No such file or directory
The way to interpret this error message:
the program cat is trying to tell you about a problem
the problem is that there is no file named >
Indeed, > is not a file. It's not intended as a file, at all. It's a shell operator to redirect output.
You need to use ProcessBuilder to redirect:
ProcessBuilder builder = new ProcessBuilder("cat", "b.jpg", "f1.zip");
builder.redirectOutput(new File("pic2.jpg"));
Process p = builder.start();
When you run a command it doesn't start a shell like bash unless you do this explicitly. This means you are running cat with four arguments b.jpg f1.zip > pic2.jpg The last two files names don't exist so you get an error.
What you are likely to have intended was the following.
String command = "sh -c 'cat b.jpg f1.zip > pic2.jpg'";
This will run sh which in sees > as a special character which redirects the output.
Because you need to start a shell (e.g. /bin/bash) which will execute your shell command, replace:
String command = "cat b.jpg f1.zip > pic2.jpg";
with
String command = "bash -c 'cat b.jpg f1.zip > pic2.jpg'";
i need to fetch the nth line of a txt file using shell script.
my text file is like
abc
xyz
i need to fetch the 2nd line and store it in a variable
i've tried all combinations using commands like :
sed
awk
head
tail
cat
... etc
problem is, when the script is called from the terminal, all these commands work fine.
but when i call the same shell script, from my java file, these commands do not work.
I expect, it has something to do with the non-interactive shell.
Please help
PS : using read command i'm able to store the first line in a variable.
read -r i<edit.txt
here , "i" is the variable and edit.txt is my txt file.
but i cant figure out, how to get the second line.
thanks in advance
edit :
ALso the script exits, when i use these "non-working" commands, And none of the remaining commands is executed.
already tried commands :
i=`awk 'N==2' edit.txt`
i=$(tail -n 1 edit.txt)
i=$(cat edit.txt | awk 'N==2')
i=$(grep "x" edit.txt)
java code:
try
{
ProcessBuilder pb = new ProcessBuilder("./myScript.sh",someParam);
pb.environment().put("PATH", "OtherPath");
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line ;
while((line = br.readLine()) != null)
System.out.println(line);
int exitVal = p.waitFor();
}catch(Exception e)
{ e.printStackTrace(); }
}
myscript.sh
read -r i<edit.txt
echo "session is : "$i #this prints abc, as required.
resFile=$(echo `sed -n '2p' edit.txt`) #this ans other similar commands donot do anything.
echo "file path is : "$resFile
An efficient way to print nth line from a file (especially suited for large files):
sed '2q;d' file
This sed command quits just after printing 2nd line rather than reading file till the end.
To store this in a variable:
line=$(sed '2q;d' file)
OR using a variable for line #:
n=2
line=$(sed $n'q;d' file)
UPDATE:
Java Code:
try {
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/full/path/of/myScript.sh" );
Process pr = pb.start();
InputStreamReader isr = new InputStreamReader(pr.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null)
System.out.println(line);
int exitVal = pr.waitFor();
System.out.println("exitVal: " + exitVal);
} catch(Exception e) { e.printStackTrace(); }
Shell script:
f=$(dirname $0)/edit.txt
read -r i < "$f"
echo "session is: $i"
echo -n "file path is: "
sed '2q;d' "$f"
Try this:
tail -n+X file.txt | head -1
where X is your line number:
tail -n+4 file.txt | head -1
for the 4th line.
OK. I've been looking everywhere on how to execute multiple commands on a single command prompt from java. What i need to do is this, but not in command line, in code.
Execute:
cd C:/Android/SDK/platform-tools
adb install superuser.apk
..Basically i want to run adb commands from a program!!! Here is my java code so far:
MainProgram.java
public class MainProgram {
public static void main(String[] args) {
CMD shell = new CMD();
shell.execute("cmd /K cd C:/Android/SDK/platform-tools"); //command 1
shell.execute("cmd /C adb install vending.apk"); // command 2
}
}
CMD.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CMD {
CMD() {
}
// THIS METHOD IS WHERE THE PROBLEM IS
void execute(String command) {
try
{
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
So what happens is...i can run the first command, but that cmd terminates and when i execute the 2nd command, a new cmd is created, hence i get an error because im not in the right directory. I tried a single string command "cmd /C cd C:/blablabla /C adb remount", but that just froze up...
Essentially, command 1 is executed and terminated, then command 2 is executed and terminated. I want it to be like this: command 1 executed, command 2 executed, terminated.
Basically i'm asking how can i run both of these commands in a row on a single command prompt???
My final target is to have a JFrame with a bunch of buttons which execute different adb commands when clicked on.
Easiest way is to make a batch file then call that from program
of course you could just say
C:/Android/SDK/platform-tools/adb install superuser.apk
there's no need to cd to a file if you name it directly
although what you are looking for is already made in ddms.bat which provides a complete visual link to adb
Create file as something.bat and set the contents to:
cd C:/Android/SDK/platform-tools
adb install superuser.apk
Then call:
Process p = Runtime.getRuntime().exec("something.bat");
all commands in the bat file are executed.