Table of Contents
You write a shell script that works perfectly on your machine. You share it with the team. It breaks immediately because your username is hardcoded in every path.
#!/bin/bash
source /home/jake/.config/app/settings.sh
cp /home/jake/templates/nginx.conf /etc/nginx/sites-available/
Classic. The fix isn’t “use variables from the start” (though you should). The fix for right now is a one-liner that makes any script portable after the fact.
The sed One-Liner
sed -i "s|/home/jake|/home/$(whoami)|g" setup.sh
That’s it. Every instance of /home/jake becomes /home/<current_user>. The | delimiter avoids escaping the forward slashes in paths (using / as a delimiter with paths containing / is a nightmare).
Make It Part of Your Install
If you distribute scripts that reference paths, add a self-patching step at the top:
#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CURRENT_USER="$(whoami)"
# Patch all config files for the current user
for f in "$SCRIPT_DIR"/configs/*.conf; do
sed -i "s|/home/[a-zA-Z0-9_-]*/|/home/$CURRENT_USER/|g" "$f"
done
The regex /home/[a-zA-Z0-9_-]*/ matches any username in a home path, not just one specific name. Way more robust than hardcoding the original username.
The Better Long-Term Fix
Obviously, the real solution is to never hardcode paths in the first place:
#!/bin/bash
HOME_DIR="${HOME:-/home/$(whoami)}"
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME_DIR/.config}"
source "$CONFIG_DIR/app/settings.sh"
Use $HOME, $USER, and $XDG_CONFIG_HOME from the start. But when you’re retrofitting an existing script or inheriting someone else’s work, sed with a regex pattern gets you portable in seconds.
Leave a Reply