nco

segmentation fault when trying to use command in a variable with ncap2


I want to use ncap2 to make a large number of variables a function of time in a netcdf file. I therefore wanted to build up the command argument in a loop and store in a bash variable command and then apply it as a variable, which I often do with cdo like this

 cdo $command in.nc out.nc 

I build up my command like this:

varlist="hfls hfss prlr prw rlds rlus rlut rsds rsdt rsus rsut clt evspsbl"

command=""
for var in $varlist ; do
    command+=" -s '${var}[time,lat,lon]=${var}'"
done
echo $command

when I then attempt to do this :

ncap2 $command in.nc out.nc 

I get a segmentation fault and core dump. But if I cut and paste the result of the echo command into the ncap2 statement,

ncap2 -s 'hfls[time,lat,lon]=hfls' -s 'hfss[time,lat,lon]=hfss' -s 'prlr[time,lat,lon]=prlr' -s 'prw[time,lat,lon]=prw' -s 'rlds[time,lat,lon]=rlds' -s 'rlus[time,lat,lon]=rlus' -s 'rlut[time,lat,lon]=rlut' -s 'rsds[time,lat,lon]=rsds' -s 'rsdt[time,lat,lon]=rsdt' -s 'rsus[time,lat,lon]=rsus' -s 'rsut[time,lat,lon]=rsut' -s 'clt[time,lat,lon]=clt' -s 'evspsbl[time,lat,lon]=evspsbl' $dir/$file /scratch/b/$USER/${file%???}_corrected.nc

It works fine... I'm sure it is something to do with the way I'm handling the strings, but my experiments trying to change around quotes etc, didn't seem to work.


Solution

  • Yes, it seems to be a shell-quoting issue. Rather than try to create a simpler analogue for testing, let me start by just asking, does it work if you use this instead?

    eval ncap2 $command in.nc out.nc