Kailash Akilesh
Kailash Akilesh

Reputation: 193

Bash command line parsing containing whitespace

I have a parse a command line argument in shell script as follows:

cmd --a=hello world good bye --b=this is bash script

I need the parse the arguments of "a" i.e "hello world ..." which are seperated by whitespace into an array.

i.e a_input() array should contain "hello", "world", "good" and "bye".

Similarly for "b" arguments as well.

I tried it as follows:

--a=*)
      a_input={1:4}
      a_input=$@
for var in $a_input
    #keep parsing until next --b or other argument is seen
done

But the above method is crude. Any other work around. I cannot use getopts.

Upvotes: 0

Views: 162

Answers (2)

user1934428
user1934428

Reputation: 22225

Adding to Etan Reisners answer, which is absolutely correct:

I personally find bash a bit cumbersome, when array/string processing gets more complex, and if you really have the strange requirement, that the caller should not be required to use quotes, I would here write an intermediate script in, say, Ruby or Perl, which just collects the parameters in a proper way, wraps quoting around them, and passes them on to the script, which originally was supposed to be called - even if this costs an additional process.

For example, a Ruby One-Liner such as

system("your_bash_script here.sh '".(ARGV.join(' ').split(' --').select {|s| s.size>0 }.join("' '"))."'")

would do this sanitizing and then invoke your script.

Upvotes: 0

Etan Reisner
Etan Reisner

Reputation: 80921

The simplest solution is to get your users to quote the arguments correctly in the first place.

Barring that you can manually loop until you get to the end of the arguments or hit the next --argument (but that means you can't include a word that starts with -- in your argument value... unless you also do valid-option testing on those in which you limit slightly fewer -- words).

Upvotes: 1

Related Questions