Link to home
Start Free TrialLog in
Avatar of ipconfig610
ipconfig610Flag for United States of America

asked on

Linux read folder names into array then execute command

I need to run a script that will look into a directory and read all the folder names into an array.

Example: below is the contents of /var/data/ and I need 'aaa','bbb','ccc','ddd' to be read into the array
/var/data/aaa/
/var/data/bbb/
/var/data/ccc/
/var/data/ddd/

I then need to create users on my Linux box

useradd -d /var/folder/aaa -s /usr/sbin/nologin aaa
useradd -d /var/folder/bbb -s /usr/sbin/nologin bbb
useradd -d /var/folder/ccc -s /usr/sbin/nologin ccc
useradd -d /var/folder/ddd -s /usr/sbin/nologin ddd
ASKER CERTIFIED SOLUTION
Avatar of Tintin
Tintin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of skullnobrains
skullnobrains

ls /var/data | while read line
do useradd -d "/var/folder/$line" -s /usr/sbin/nologin "$line" || exit 1
done

will also work if you have spaces in the directory names and if you have many entries in the directory. will also return false if something went wrong. but will not be limited to directories because i lazily used ls.

this one is nicer

{ cd /var/data && find . -maxdepth 1 -type d -exec useradd -d "/var/folder/{}" -s /usr/sbin/nologin "{}" \; ; }

 give points to tintin.


@tintin
find * -maxdepth 0
find . -maxdepth 1
are both ok, but
find * -maxdepth 1
is not as you're getting one level too deep.