I want to loop through a list of directories (a subset of the directories in a folder) and do operations with them. However, for some reason it is not working. Here is the code where I am just echoing all of them:
#!/bin/bash
cd images
array=$(ls -d *)
selection=(${array[@]:1:12})
cd ..
for sub in ${selection[@]}
do
echo $sub
mkdir $HOME/Projects/PhD/0_project/fMRI/scans/temp/temp_$sub
done
The ouptut I get for the echo command is:
04
306
307
3
And the folders: temp_3, temp_04, temp_306, temp_307
HOWEVER, if I run each single line in bash in the termiinal (interactive mode, no script) I do get the correct output for the echo command:
306
307
308
309
310
311
312
314
317
318
323
324
And for the mkdir command: temp_306, temp_307... temp_324
Any idea about this strange and inconsistent behaviour? What am I missing?
Thanks for your help.
array=( */ )is a much less buggy way to put folder names into an array.array=( "${array[@]%/}" )to postprocess if you don't want the trailing slashes. Parsinglsis bad juju, and doing it badly defeats the whole point of using arrays in the first place (their ability to accurately store arbitrary strings). Though your current code isn't actually using arrays at all.imageslook like?