Skip to content
Advertisement

How to create file with folders for all users in home directory

So for example we have 4 users in /home directory:

user1 user2 user3 user4

What I am trying to achieve is that I create directories with files inside for all these users.

/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:

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:

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:

for home in /home/*; do
  mkdir -p "$home/dir/anotherdir" &&
    touch "$home/dir/anotherdir/somefile"
done
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement