0

I need to scan through a file which has some unix shell commands and its output. I need to extract the list of unix commands mentioned throughout the file and list them down onto a different file. One way to achieve it to scan through the file for some specific list of commands and if present to redirect them to a different file. But this gets difficult as the list kept growing. Any other ideas in this line. TIA

user3894937
  • 73
  • 2
  • 7
  • Assuming that what you want is to determine which commands an arbitrary script can invoke during its execution, a correct implementation of this is provably impossible if you need it to cover all the corner cases (including `eval` usage). What are the real-world design constraints and requirements, so we can figure out if a good-enough implementation exists (and whether it will *actually* be good enough)? – Charles Duffy Nov 21 '16 at 16:50
  • ...if you could clarify the question enough that we don't need to make assumptions about what it is you are or are not asking for, that would be helpful. – Charles Duffy Nov 21 '16 at 16:55
  • 1
    Can you give an example of the file's contents? Is it just the output of the `script` command? If each command is preceded by a prompt string, then it's fairly easy to extract the commands, although it won't be perfect. – Mark Plotnick Nov 21 '16 at 18:39
  • An example file would be something like - >pwd /bin/dir1 >date >echo "hi" hi. In this case I want my script to scan through this file and identify that three unix commands are used in this file and save those commands onto a new file. – user3894937 Nov 22 '16 at 06:10
  • So whatever the file contents, ignoring the rest only the unix commands should be identified. and either copy the command alone onto a different file or simply copy the whole line onto a different file. – user3894937 Nov 22 '16 at 06:14

1 Answers1

1

You can get a list of all commands available in bash with compgen. If you want to use a whitelist approach, you could store the output of compgen -ac (aliases and commands) in a file and then check each token in your input file against that list.

More details on usage of compgen can be found on this answer.

Community
  • 1
  • 1
Matt
  • 646
  • 4
  • 11
  • Hmm. The way I read it, the OP is trying to figure out which commands can possibly be invoked during a specific script's execution (as via textual/static analysis of that script), as opposed to which commands exist on the system -- but the question is indeed a bit ambiguous here. – Charles Duffy Nov 21 '16 at 16:52