Bash Script: Pull the Username from the Path, or Determining Whose Home Directory We’re In


I needed a bash script to quickly update the ownership of a bunch of files, based on what directoy I’m currently in.

The username is pulled from the present working directory (pwd): /home/SOMEUSER/the/rest/of/the/path

Here’s the bit of code that does it:

USR=`pwd | sed -e 's@^/home/([^/]*)/.*@1@g'`

It basically takes the current directory and replaces anything that’s not /home/HERE/rest/path with nothing.

Here’s the rest of the script, which lets you specify the username, or let it be pulled from the current path.

So you can either do web-perms SOMEUSER. Or if you’re in the /home/SOMEUSER/ directory then it will pull it automatically from there by web-perms.

#!/bin/bash
if [ -z "$1" ]; then
        USR=`pwd | sed -e 's@^/home/([^/]*)/.*@1@g'`
        if [ -z "$USR" ]; then
                USR=$USER
        fi
else
        USR=$1
fi
echo Setting ${USR}.www-data (664/775) ...
chown -R ${USR}.www-data .

Note that this changes the group to www-data — change this if you want something else, or if you want the specified USR to also be the group, change www-data to chown -R ${USR}.${USR} .