-1

i want to grab the names of directorys to create a tar.gz file for each

for example, all directorys with beginning with A:

count = 10

for ((k = 1 ; k < $count ; k++));
do
    tar -cf ADIRNAME.tar.gz ADIRNAME
    sleep 1
done

how can i do this?

mostworld77
  • 427
  • 4
  • 7
  • 27
  • Use `find` to get the directories? – devnull May 18 '14 at 18:21
  • 1
    You can iterate over directories with `for dir in */; do echo "$dir"; done` – that other guy May 18 '14 at 18:28
  • What do you mean by "all directorys": All directories anywhere on the filesystem? All directories in a specific folder? All directories anywhere under a specific folder? – ruakh May 18 '14 at 18:41
  • in a specefic folder. It should grab foldername with begining the letter A,use this folder name to create a tar file and then do the other commands.. – mostworld77 May 18 '14 at 19:00
  • What's with the `for` loop? Do you expect (or suppose by way of an example) that there will be ten directories? Why the `sleep`? – tripleee May 19 '14 at 02:41

2 Answers2

3

This will create a tarball for each A* directory.

for dir in A*/; do
    tar -cf "${dir%/}".tar.gz "$dir"
done

The wildcard expands to a list of directory names to loop over. The trailing slash which sets the matches off as directories will be included in the expansion; we trim it from the tarball's filename with a simple variable substitution (${variable%suffix} expands to the variable's value with suffix trimmed from the end if present; there is also a corresponding ${variable#prefix} and a number of other substitutions; see your shell's man page.)

The double quotes are mandatory, although the script will work without them as long as there are no file names with whitespace in them. This is a common oversight even in many shell scripting tutorials.

tripleee
  • 175,061
  • 34
  • 275
  • 318
1

it's not exactly clear what you need to do, but here are some bits to build upon:

find all directories:

find -maxdepth 1 -type d

find all directories starting with a certain letter:

find -maxdepth 1 -type d -name 'X*'

now you can get the list of the first letters:

for n in `find -maxdepth 1 -type d`; do echo ${n:2:1}; done | sort -u

and finally, perform tar'ing with those letters.

Pavel
  • 7,436
  • 2
  • 29
  • 42