Question

I'm trying to store the results of a command in a variable, but I can't figure out the correct syntax. This command works perfectly:

echo "-868208.53 -1095793.57 512.30" | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326

This is how I've tried to use this example and applied it to my data. However, the outcord assignment is wrong:

#!/usr/bin/bash
filename="$1"
while read -r line
do
    name=$line
    a=( $name )
    coord= ${a[1]} ${a[2]}
    outcoord= $("echo $coord | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326")
    echo $outcoord
done < "$filename"

A sample error I get:

remap.sh: line 7: -515561.05: command not found
remap.sh: line 8: echo  | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326: command not found
remap.sh: line 7: -515542.01: command not found
remap.sh: line 8: echo  | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326: command not found

Sample data:

1 -515561.05 -1166540.03
2 -515542.01 -1166548.76
3 -515519.61 -1166552.19
4 -515505.29 -1166550.25
5 -515477.05 -1166546.82
6 -515431.12 -1166534.06
7 -515411.45 -1166517.39

How do I assign the result of a command to the variable outcoord?

Was it helpful?

Solution

You have numerous problems out there. The first in the following line:

coord= ${a[1]} ${a[2]}
  • Never put spaces around =.
  • Quote variables if those contain spaces.

Replace the following lines:

name=$line
a=( $name )
coord= ${a[1]} ${a[2]}
outcoord= $("echo $coord | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326")
echo $outcoord

with

outcoord=$(echo "${line[@]}" | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326)
echo "$outcoord"

and it should be good.

If you want only last two elements of the array, you could say:

outcoord=$(echo "${line[1]} ${line[2]}" | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326)

And, instead of:

while read -r line

say

while read -a line

which would assign the line read to an array line.

OTHER TIPS

Try removing the double quotes; i.e.:

    outcoord=$(echo $coord | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326)

Otherwise bash interprets the whole string as the name of the command.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top