LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   how to change directory using bash or other simple language (http://www.linuxquestions.org/questions/programming-9/how-to-change-directory-using-bash-or-other-simple-language-724610/)

packets 05-08-2009 03:25 AM

how to change directory using bash or other simple language
 
I was task to change the home dir of the thousand of users in my server. The new directory will be according to the first letter of their username. If my username is nelson, the home dir must be /emails/n/nelson. If the login name is fred, the home dir must be /emails/f/fred.

As of the moment, current dir was only located at /home dir such as /home/fred.

Can anyone give a hint on how would I do this? My problem is getting the first character of their username and putting it in their designate folder which was also according to the first characted of their domain.

I tried this script but I encounter a problem

#!/bin/bash

USER=`cat /etc/passwd | grep home | awk -F: '{print $1}'`
LETTER=`cat /etc/passwd | grep home | sed -r 's/(.)[^.]*\.?/\L\1/g'`

for letter in $LETTER;do
for user in $USER;do
if [ "$letter" == t ]; then
mkdir /emails/$letter/$user
mkdir /emails/$letter/$user/new
mkdir /emails/$letter/$user/cur
mkdir /emails/$letter/$user/tmp
echo "CHECKING T"
usermod -d /emails/$letter/$user $user
elif [ "$letter" == n ]; then
mkdir /emails/$letter/$user
mkdir /emails/$letter/$user/new
mkdir /emails/$letter/$user/cur
mkdir /emails/$letter/$user/tmp
usermod -d /emails/$letter/$user $user
echo "CHECKING N"
fi

done


done

colucix 05-08-2009 03:39 AM

Don't use two for loops, otherwise for each letter a new home directory is created for all the users under each letter. Just loop over the users and extract the first letter from the username inside the loop. Actually you don't need neither the if/elif statement, until the commands are the same for all the letters:
Code:

#!/bin/bash
while read user
do
  letter=$(echo $user | cut -c1)
  mkdir -p /emails/$letter/$user/new /emails/$letter/$user/cur /emails/$letter/$user/tmp
  echo "CHECKING T"
  usermod -d /emails/$letter/$user $user
done < <(awk -F: '/home/{print $1}' /etc/passwd)


packets 05-08-2009 03:46 AM

@colucix

Thanks for the reply. Will post here if I encounter some problem.

I'm still checking the scripts for some additional commands. It was such a headache migrating to new mail servers

ghostdog74 05-08-2009 04:28 AM

if you have Python, here's an alternative solution
Code:

#!/usr/bin/env python
import os
directory="/emails"
for line in open("/etc/passwd"):
    line=line.strip().split(":")
    if "home" in line[5]:
        letter=line[0][0]
        os.makedirs(os.path.join(directory,letter,line[0]))



All times are GMT -5. The time now is 09:07 AM.