简体   繁体   中英

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?

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/

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

It may be easier to make a link to the source directory, and then you can just update it in one place.

Just set up each users directory so that the common files are all pulled from a directory called common_files (or whatever you like), and then run this command in each home directory:

ln -s /location/of/files/they/need common_files

update /location/of/files/they/need and it automatically propagates.

With bash you can actually make this pretty short and simple. To list the current directory and store it into an array:

ls . | readarray i

or

ls . | bash -c 'readarray i'

To use the data:

ls . | bash -c 'readarray i && for j in ${i[*]}; do <-command->; done'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM