Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINUX: List all directories, push into a bash array

Here's the end result I am trying to:

I have over 15 users of an cloned instance of my application, sometimes I need to update files (they pretty much all stay the same--everything is dynamic. This is for updates/new features). I wrote a pretty simple bash script that I had to manually put each user from /home/ into the array. But I need this to scale.

How can I take a directory listing (something like a LS command) feed ONLY DIRECTORY names into then a bash array. Likely i'll want this command in the bash file though, because I'll want it to grab all users in the /home/ directory, push into the array (eg: webUsers( adam john jack )

Here's a snapshot of what my current script looks like (non-dynamic user listing)

webUsers( adam john jack )

for i in "${webUsers[@]}"
do 
 cp /home/mainSource/public_html/templates/_top.tpl /home/$i/public_html/templates
done 

How do I achieve this?

like image 869
Snow_Mac Avatar asked Nov 27 '25 20:11

Snow_Mac


2 Answers

Do this:

webUsers=(/home/*/)

and the contents will look like:

$ declare -p webUsers
declare -a webUsers='([0]="/home/adam/" [1]="/home/jack/" [2]="/home/john")'
$ echo ${webUsers[1]}
/home/jack/

Or, if you don't want the parent directory:

pushd /home
webUsers=(*/)
popd

and you'll get:

$ declare -p webUsers
declare -a webUsers='([0]="adam/" [1]="jack/" [2]="john")'
$ echo ${webUsers[1]}
jack/
like image 123
Dennis Williamson Avatar answered Nov 30 '25 08:11

Dennis Williamson


The following script will loop over all users with directories in /home. It will also unconditionally try to create the /public_html/templates directory. If it doesn't yet exist, it will get created. If it does exist, this command does essentially nothing.

#!/bin/bash

cd /home
userarr=( */ );

for user in "${userarr[@]%*/}"; do
   mkdir -p "/home/${user}/public_html/templates"
   cp "/home/mainSource/public_html/templates/_top.tpl /home/${user}/public_html/templates"
done
like image 32
SiegeX Avatar answered Nov 30 '25 08:11

SiegeX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!