So for example we have 4 users in /home directory:
JavaScript
x
user1 user2 user3 user4
What I am trying to achieve is that I create directories with files inside for all these users.
JavaScript
/home/user1/dir/anotherdir/somefile
/home/user2/dir/anotherdir/somefile
For one user I can try something like: mkdir -p /home/user/dir/anotherdir && touch /home/user/dir/anotherdir/somefile
. But I want a dynamic solution when I don’t know how many users are and nor their names.
Advertisement
Answer
If you are using bash, you can use brace expansion to explicitly define each user:
JavaScript
mkdir -p /home/{user1,user2,user3,anotheruser}/dir/anotherdir &&
touch /home/{user1,user2,user3,anotheruser}/dir/anotherdir/somefile
If you must use POSIX features only, use a loop:
JavaScript
for user in user1 user2 user3 anotheruser; do
mkdir -p "/home/$user/dir/anotherdir" &&
touch "/home/$user/dir/anotherdir/somefile"
done
If you want to loop over all currently existing usernames, modify the loop slightly:
JavaScript
for home in /home/*; do
mkdir -p "$home/dir/anotherdir" &&
touch "$home/dir/anotherdir/somefile"
done