Search code examples
bashsedbrace-expansion

How to use variable expansion in shell script


I have a script that looks like this

#!/bin/bash
#
for i in `seq -w 22 35`
do
  cd /folder/d"$i"
  generate_XDS.INP d"$i"_001.img.bz2 #makes a text file "XDS.INP" 
  u=`grep UNIT_CELL_CONSTANTS /folder/d${i-1}/CORRECT.LP | tail -n 1` #get info from previous run
#u is supposed to be something like: UNIT_CELL_CONSTANTS=    79.08    79.08    37.02  90.000  90.000  90.000
  sed -e "s:NAME_TEMPLATE_OF_DATA_FRAMES=./d${i}_001.img.bz2:NAME_TEMPLATE_OF_DATA_FRAMES=./d${i}_???.img.bz2:" -e 's:DATA_RANGE=:DATA_RANGE=1 100:' -e 's:SPOT_RANGE=:SPOT_RANGE=1 100:' -e 's:SPACE_GROUP_NUMBER=0:SPACE_GROUP_NUMBER=96:' -e "s:UNIT_CELL_CONSTANTS= 70 80 90 90 90 90:${u}:" XDS.INP > a #Change a few lines in input so that the job can run. 
  mv a XDS.INP
done

The problem is the "u=line". I used to have something like this, without the u=line and the two last substitute commands in the sed line, and it worked. Now u appears empty and the sed command does not end successfully. How can I fix this? I know this has something to do with the {brace} expansion. But I do not know how to proceed.


Solution

  • I don't know if that's the actual problem here, but ${i-1} will not evaluate an arithmetical expression, as you likely intended.

    Either use $(( i - 1 )), which will work in most shells (like bash, dash, etc.) and is the preferred syntax for arithmetical expressions or use $[ i - 1 ], which will work in bash, but not in some other shells. Also, the latter syntax is discouraged, as pointed out by Charles Duffy's comment.