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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
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[@]}"
Thanks a lot friend it helped me!
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

Comments

0

you can try this way also.

for i in $(ls /myself/*)

do

tar -cvfz $f.tar.gz /myfile2

done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.