Home > Back-end >  Cannot put all the text in the same line to compile a program using bash
Cannot put all the text in the same line to compile a program using bash

Time:09-01

My objective in this script is put all the text on the same line to compile a OCaml file, but i as a new bash user, dont know how to do this. Anyone can help?

#!/bin/bash

function argv {
  ocamlopt -o
  for (( i=0; i < $#; i   )) 
  do 
    "${BASH_ARGV[i]}"
  done
}

argv "$@"

error when executed:

option '-o' needs
an argument.
Usage: ocamlopt <options> <files>
Try 'ocamlopt --help' for more information.
./comp.sh: line 7: teste.sh: command not found
./comp.sh: line 7: teste: command not found

CodePudding user response:

Inside do ... done should appear commands that you want bash to execute for you. But you are generating arguments there for a previous command. That isn't going to work, as you have seen.

You also don't need to generate your list of arguments. It already exists under the name "$@" as @JohnBollinger and @Shawn point out.

Since your argv function uses BASH_ARGV, it is getting the original arguments from the command line. In other words, it ignore the arguments that are passed to it. Let's assume you want it to look at its arguments instead.

Let's also assume this is just an example of something a little more complicated you want to do.

Well then, it's actually pretty tough to generate a series of separate arbitrary arguments (if they can contain spaces or similar). If you're willing to assume that the arguments are all well behaved (no spaces or the like) you can build up an argument string like this:

#!/bin/bash

function argv {
  MY_ARGS=''
  for MY_ARG in $*; do
    MY_ARGS="$MY_ARGS $MY_ARG"
  done
  ocamlopt -o $MY_ARGS
}

argv "$@"
  • Related