Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

command line argument from file content with quote

Tags:

bash

shell

I have a file containing command line arguments that I would like to pass to another script.

But this file contain element such as "param 1" param2 param3.

Let's call the file with arguments test.tmp and the script file script.sh.

If I do:

script.sh -p `cat test.tmp` -other_params 1 2 3

The script.sh receives after p:

  1. "param
  2. 1"
  3. param2
  4. param3

But I would like:

  1. param 1
  2. param2
  3. param3

Any idea?

Small precision: assume that script.sh is not modifiable. The solution must take place in the shell.

like image 434
Marc Simon Avatar asked Jul 08 '15 20:07

Marc Simon


4 Answers

ASSUMPTION: test.tmp needs to contain a parameter per line with this approach.

You may use xargs with a linefeed delimiter:

cat test.tmp | xargs -d '\n' script.sh -p
like image 157
Manuel Barbe Avatar answered Sep 19 '22 04:09

Manuel Barbe


You can wrap the command in eval:

eval "script.sh -p `cat test.tmp` -other_params 1 2 3"

$ cat test.tmp 
"params 1" param2 param3

$ cat script.sh 
#!/bin/bash
echo $1
echo $2
echo $3
echo $4
echo $5
echo $6

$ eval "./script.sh -p `cat test.tmp` other_params 1 2 3"
-p
params 1
param2
param3
other_params
1
like image 25
Nathan Wilson Avatar answered Sep 19 '22 04:09

Nathan Wilson


Lay out your file like this:

param 1
param2
param3

then read it into an array like this:

mapfile -t params < file

then call your script like this:

script.sh -p "${params[@]}" -other_params 1 2 3

The advantage of this approach is that it only uses built-in bash commands and doesn't require an eval.

To do it all in one line, you can use:

mapfile -t params < file && script.sh -p "${params[@]}" -other_params 1 2 3

i.e. use && to execute the second command if the first one succeeded.

like image 28
Tom Fenech Avatar answered Sep 17 '22 04:09

Tom Fenech


Using grep with Perl regex:

IFS=$'\n'; ./script.sh -p $(grep -woP '((?<=")[^"]*(?="))|([\S]+)' test.tmp)

Example:

script.sh:

#!/bin/bash
echo "$1"
echo "$2"
echo "$3"
echo "$4"
...

Output:

-p
param 1
param2
param3
...

Note: It will change the IFS of the current shell (where you are running these commands).

like image 35
Jahid Avatar answered Sep 18 '22 04:09

Jahid