1

How do I execute commands by running a file in Linux? I need to run the following commands:

cd /bin
java -cp main

What should the file extension be?

Ulfalizer
  • 4,664
  • 1
  • 21
  • 30
  • It could be any extension but the convention (in bash) is to use `.sh` (and make the file executable, of course...) – Nir Alfasi Mar 22 '15 at 03:56
  • Use `ProcessBuilder`, it will allow you to define the execution context (directory) from which the command should be executed, for [example](http://stackoverflow.com/questions/28955020/compiling-and-executing-using-exec-in-java-fails-using-command-that-works-from-t/28955036#28955036) and [example](http://stackoverflow.com/questions/15218892/running-a-java-program-from-another-java-program/15220419#15220419) – MadProgrammer Mar 22 '15 at 03:58

2 Answers2

2

Welcome to bash scripting.

What you want to achieve, is one of the most important features of any terminal, to execute commands from a file.

In Linux, you need not have any particular extension for a bash file, although the .sh extension is customary.

Create a file with any name, (I'll choose script.sh)

The contents:

#!/bin/bash
cd /bin
java -cp main

Make it executable now:

$ chmod a+x script.sh

Now execute the script:

$ ./script.sh

Voila! Your first bash script. You can learn more about bash scripting here.

EDIT:

Since the OP is running Raspian Wheezy, this can help him create scripts.

Community
  • 1
  • 1
shauryachats
  • 9,975
  • 4
  • 35
  • 48
0

Running linux commands in java:

Doing this is possible with java.

Runtime.exec() method should work for you.

Write a shell script file and invoke it from the java code like this...

{
   Process pro = Runtime.getRuntime().exec("./script.sh");                        
   pro.waitFor();
}

The script that you create contains your desired command by following the bash introduction given in the other answer.

Community
  • 1
  • 1