-2

I am reading some commands from input and executing at run-time in my java program . If there is any syntax or semantic errors it will fail at run-time. Instead of that I want to fail early. So I want to validate commands before execution.

How can i do that?? Is there any simple way.

Ex:

grep -P -o "cpums=[^ ]+" | cut -f2 -d= | cut -f1 -d"]" | awk '{a+=$1;}
END {print a;}

Here the single quote (') is missed at the end of this command. It will fail at run-time in my java program. It would be great if it can fail early. So i just want to validate every command at beginning of my program.

I am looking for an optimal way.

Rajesh Barri
  • 502
  • 5
  • 21

4 Answers4

2

No, there is no simple way. There is a hard way, which involves you coming up with a set of rules and using some sort of parser. There's an inefficient way, which involves trying to execute the command just to see if it works or not. There may be other ways, but I don't think any of them will be simple.

Have you tried googling for this? There's a small but non-zero possibility that somebody else has already written it.

Eric Stein
  • 13,209
  • 3
  • 37
  • 52
1

The best way to check the syntax and the parameters is to parse the user input with a regular expression corresponding to what you're expecting.

If it does not match wath you're waiting for, then you can prompt the "usage instructions" to the user.

0

Try this :

sh -n yourscriptfile
bash -n yourscriptfile

set -u also helps in catching typos and uninitialized variables

Srini V
  • 11,045
  • 14
  • 66
  • 89
0

Oh, that is really "easy".

  1. Take the bash grammer, e.g. from here or take a ANTLR grammar form here
  2. Port the grammar to java. You can strip out all the C parts and port the core grammar from the real bahs grammar or use the prefactored ANTLR grammar. Use your grammar with ANTLR, xText or parser combinators. All three solutions need external tools.
  3. Before you run a bash command, you can validate it with your grammar.
stefan.schwetschke
  • 8,862
  • 1
  • 26
  • 30