0

How can I pass each one of my repository files and to do something with them?

For instance, I want to make a script:

#!/bin/bash
cd /myself
#for-loop that will select one by one all the files in /myself
#for each X file I will do this:
tar -cvfz X.tar.gz /myself2
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

3 Answers3

0

So a for loop in bash is similar to python's model (or maybe the other way around?).

The model goes "for instance in list":

for some_instance in "${MY_ARRAY[@]}"; do
    echo "doing something with $some_instance"
done

To get a list of files in a directory, the quick and dirty way is to parse the output of ls and slurp it into an array, a-la array=($(ls)) To quick explain what's going on here to the best of my knowledge, assigning a variable to a space-delimited string surrounded with parens splits the string and turns it into a list.

Downside of parsing ls is that it doesn't take into account files with spaces in their names. For that, I'll leave you with a link to turning a directory's contents into an array, the same place I lovingly :) ripped off the original array=($(ls -d */)) command.

Tyler Stoney
  • 418
  • 3
  • 13
  • Hello! I have this in a Script: `for i in "${array=($(ls))"; do tar -cvfz "$i.tar.gz" done` but it does not work :o Even if I change `tar -cvfz i.tar.gz` with `echo $i` it prints nothing – user13425812 Apr 28 '20 at 16:12
  • Take it one step at a time. The line ```array=($(ls))``` should come the line before; it creates a variable named "array" which can be accessed in your for loop like ```for i in "${array[@]}"``` – Tyler Stoney Apr 28 '20 at 16:28
  • Thanks a lot friend it helped me! – user13425812 Apr 28 '20 at 17:31
0

you can use while loop, as it will take care of whole lines that include spaces as well:

#!/bin/bash
cd /myself
ls|while read f
do
tar -cvfz "$f.tar.gz" "$f"
done
Ron
  • 5,900
  • 2
  • 20
  • 30
0

you can try this way also.

for i in $(ls /myself/*)

do

tar -cvfz $f.tar.gz /myfile2

done

Ratnam
  • 11
  • 3