I am trying to write a bash 开发者_StackOverflowscript that does the following:
- Enumerates through list of files in a directory, that match a specified pattern
- Creates a tar file containing the matching files
- Removes (i.e. deletes) the matched files from their source directories
To keep things simple, I intend to use a hard coded list of directories and file patterns
This is what I have come up with so far:
#!/bin/bash
filenames[0]='/home/user1/*.foo'
filenames[1]='/some/otherpath/*.fbar'
for f in ${filenames[@]}
do
echo "$f"
done
However, I am unusure on how to proceed from this point onward. Specifically, I need help on:
- How to glob the files matching the pattern $f
- How to add the ENTIRE list of matching files (i.e. from all directories) to a tar file in one go
Regarding deleting the files, I am thinking of simply iterating through the ENTIRE list obtained in step 2 above, and 'rm' the actual file - is there a better/quicker/more elegant way?
PS:
I am running this on Ubuntu 10.0.4 LTS
If you want to use a loop because you have many directories, you can use the -r
option to append to the tar file. You can also use --remove-files
to remove files after adding them to the archive.
filenames[0]='/home/user1/*.foo'
filenames[1]='/some/otherpath/*.fbar'
for f in "${filenames[@]}"
do
tar -rvf --remove-files foo.tar $f
done
If you don't have the --remove-files
option, use rm $f
after the tar
command.
tar(1)
supports an --remove-files
option that will remove the files after adding them to the archive.
Depending upon what you're trying to do with your shell globs, you might be able to ignore doing all that extra work there, too. Try this:
tar cf /dir/archive.tar --remove-files /home/user1/*.foo /some/otherpath/*.fbar
精彩评论