Bad substitution error for running a bash command for many files in a folder in for loop

I have some files (image-1.nii, image2.nii, etc.) in a folder (INPUT_DIRECTORY) which are inputs to a command, and the result files should be saved in two other directories (BIAS_DIRECTORY,SEGMENTATION_N4_IMAGES).

These are the command that I tried to write:

 #!/bin/bash
INPUT_DIRECTORY=${PWD}/Images
OUTPUT_DIRECTORY=${PWD}/Output
BIAS_DIRECTORY=${PWD}/BIAS
SEGMENTATION_N4_IMAGES=${PWD}/N4
mkdir -p $OUTPUT_DIRECTORY
mkdir -p $BIAS_DIRECTORY
mkdir -p $SEGMENTATION_N4_IMAGES
N4=${ANTSPATH}/N4BiasFieldCorrection
N4_CONVERGENCE="[100x100x100x100,0.0000000001]"
N4_SHRINK_FACTOR=2
N4_BSPLINE_PARAMS="[200]"
DIMENSION=3
NIIEXT=".nii"
NIIFILES="($INPUT_DIRECTORY/*$NIIEXT)"
for FILE in "${NIIFILES[@]}"; do FILENAME="$(basename $FILE $NIIEXT)" ${N4} -d ${DIMENSION} -i ${FILENAME}.nii -s ${N4_SHRINK_FACTOR} -c ${N4_CONVERGENCE} -b ${N4_BSPLINE_PARAMS} -o ["(${SEGMENTATION_N4_IMAGES}/${FILENAME})".nii,"(${BIAS_DIRECTORY}/${FILENAME})".nii.gz] --verbose 1
done

I am getting error for this line for FILE in "${NIIFILES[@]}"; do (error:Bad substitution) and I am not sure whether my code is correct or not. Could experts please have a look? Thanks

2

2 Answers

Similar to @oliv's response, you need to declare it as an array. A safer way to declare it as an array is this:

declare -a NIIFILES=( "$INPUT_DIRECTORY"/*.nii )

It gives slightly more control over the content in that it marks it unquestionably as an array to the next developer to see it.

A more shorthand way, or if space may later become a problem (from too many files/folders in the tree) you could use:

for FILE in "INPUT_DIRECTORY"/*.nii; do FILENAME="$(basename $FILE $NIIEXT)" ${N4} -d ${DIMENSION} -i ${FILENAME}.nii -s ${N4_SHRINK_FACTOR} -c ${N4_CONVERGENCE} -b ${N4_BSPLINE_PARAMS} -o ["(${SEGMENTATION_N4_IMAGES}/${FILENAME})".nii,"(${BIAS_DIRECTORY}/${FILENAME})".nii.gz] --verbose 1
done

Of course, it's all up to preference. These and similar structures can be seen in this stackoverflow question.

Hope this helps.

Your NIIFILES is declared as a string and not as an array.

Assuming file don't have space in their filename, you could use:

NIIFILES=( "$INPUT_DIRECTORY"/*.nii )
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like