U
U
uaf0x2016-02-23 17:50:52
bash
uaf0x, 2016-02-23 17:50:52

How to get all directories into an array and walk through them with the analog of foreach?

Actually, connoisseurs :)
How to organize a loop through to use each element?
This is what it is now but it shows everything as 1 element
declare -a files=`ls PATH`

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Nemiro, 2016-02-23
@uaf0x

You can use find :

find /etc/* | while read -r path; do 
  if ; then 
    printf "Файл: %s\n" "$path"; 
  elif ; then
    printf "Мамка: %s\n" "$path"; 
  fi
done

/etc/* - search path. In this case, all files and folders in the /etc directory will be retrieved .
With the help of additional parameters, you can limit the selection.
For example, limit to the current level: -maxdepth 0.
Find directories only: -type d.
Or just files: -type f.
find /etc/* -maxdepth 0 | while read -r path; do 
  if ; then 
    printf "Файл: %s\n" "$path"; 
  elif ; then
    printf "Папка: %s\n" "$path"; 
  fi
done

For details see find --help.
If you still need an array, you can form it in a loop:
declare -a files

find /etc/* -maxdepth 0 -type f | while read -r path; do
  files+=("$path")
done

Z
Zr, 2016-02-24
@Zr

>declare -a files=`ls $MY_PATH`

cd "$MY_PATH"
files=( */ )

(In general, I don’t know of a single example when using a utility lsin a Bash program is justified.)
But if you need a cycle through them, then the array is, in fact, useless here:
for file in */; do 
    echo "$file"
done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question