Bash script for iterating through defined set of file names and performing commands

I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;

Then the next command is analogous:

/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command. Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.

Answers


If the list is predefined and you're not iterating over every directory that exists (in other words, if a directory named 99 exists but it's not in your list you want to exclude it), you can iterate over the list:

list="10 12 13 14 18 24"; for dir in $list; do cd "$dir"; do_something "foo $dir bar"; done

or an array:

array=(10 12 13 14 18 24); for idx in ${!array[@]}; do cd "${array[idx]}"; do_something "foo ${array[idx]} bar"; done

You can do previous or next array elements like this: ${array[idx-1]} or ${array[idx+1]} if you do appropriate checks to make sure you're not trying to retrieve an element with a negative index (an index beyond the last element will return a null).

or:

array=(10 12 13 14 18 24); for dir in ${array[@]}; do cd "$dir"; do_something "foo $dir bar"; done

which is essentially the same as the list example above.


The no brainer way is:

for dir in [0-9][0-9]/; do
    cd "$dir"
    cp /home/files/*Session${dir%/}.* .
    svn add *Session${dir%/}.*
    svn commit
    cd ..
done

This will only iterate over directories which are composed of 2 digits.


base=$PWD; for num in *; do cd $base/$num; cp /home/files/*Session${num}.* .; svn add *Session${num}.*; svn commit; done


Time for the find-based solution.

find . -maxdepth 1 -regextype posix-extended -type d -regex '.*/[0-9]{2}$' -exec \
    bash -c 'dir=${1##*/}
    cd $1 
    cp /home/files/*Session{$dir}.* . 
    svn add *Session${dir}.* 
    svn commit'  -- {} \;

EDIT: now more findy than ever.


Need Your Help

Why can't I pass a variable to Model's constructor in Code Igniter?

php oop codeigniter codeigniter-2

It seems that it is impossible to pass a variable to a Model's Constructor in Code Igniter. Maybe I'm missing something in MVC or Code Igniter, but I don't understand what.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.