P
P
Pavel Belyaev2018-07-26 14:48:43
bash
Pavel Belyaev, 2018-07-26 14:48:43

bash function arguments with spaces from variable?

The question is confusing, in general, what happens to me is something like this

while read  line || ;
do
  l=$(echo "${line}")
  lo_m "${loc_file}" ${line}
done < "${appname}.loc"

those. a line is read from the file that contains something like this
"string" "value vvv"
Now let's take an example so that everyone understands everything
#!/bin/bash
myvar="\
\"str1\" \"var1 vvv\"
\"str2\" \"var2 www\""

echo "$myvar";

myfunc(){
echo "$1 :: $2 :: $3"
}

echo "$myvar" | while read -r line;
do
  myfunc "str multi" $line
done

And what will we get in the output?
the first argument "str multi" is passed as one and the quotes are removed, the second argument is passed with quotes, and the third is torn by two more spaces, although it is enclosed in quotes
"str1" "var1 vvv"
"str2" "var2 www"
str multi :: "str1" :: "var1
str multi :: "str2" :: "var2

How to pass pre-prepared arguments from a variable or file so that they are adequately parsed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Saboteur, 2018-07-26
@PavelBelyaev

In the file you don't have different arguments, but just a string.
You pass it as a string and expect the read command to parse it into separate arguments.
But read doesn't do that.
The correct way is to use CSV files that will contain:
str1,var1 vvv
str2,var2 www
And then you can parse by commas (or take any other character that does not occur in your data as a separator)

while read; do
  echo ${REPLY} | cut -d "," --output-delimiter ":" -f 1,2
done <<<'str1,var1 vvv
str2,var2 www'

If you want the file to be parsed in quotes, write a parser on the read line, or already inside your parser function (you can even set the same cut on quotes, and skip intermediate columns):
while read; do
  echo "${REPLY}" | cut -d "\"" --output-delimiter ":" -f 2,4
done <<<'"str1" "var1 vvv"
"str2" "var2 www"'

But this is a bike.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question