Simplify Chown Command Using Bash Script

Chown. Stands for « change ownership, » and it’s all about control. This nifty little command empowers users to switch the ownership of files and directories like a boss. It’s like having the keys to the digital realm, where you can dictate who gets to read, write, or execute your precious files. I do a lot of […]

Server + Linux

Chown. Stands for « change ownership, » and it’s all about control. This nifty little command empowers users to switch the ownership of files and directories like a boss. It’s like having the keys to the digital realm, where you can dictate who gets to read, write, or execute your precious files.

I do a lot of chown-ing everyday. That repetitive nature of the command can be a bit cumbersome. So, i need to prune it down to just several characters.

We need to create a bash script for certain.

  1. Open a text editor, like nano, and create the chw script:
nano chw
  1. Add the following content to the chw script:
#!/bin/bash

if [ $# -eq 1 ]; then
    user="$1"
    chown -R "$user":"$user" .
else
    echo "Invalid argument. Usage: ch <username>"
fi
  1. Save the file and exit the text editor.
  2. Make the script executable:
chmod +x chw
  1. Move the script to a directory in our PATH (e.g., /usr/local/bin or ~/bin) to be able to run it from any location.
sudo mv chw /usr/local/bin

Now we can use the ch command followed by the desired username to change ownership to that user recursively. For example:

chw mike

Replace mike with any other valid username as needed. Be cautious while using this script, as changing ownership can have significant consequences. Ensure that we only run the command in the appropriate directory where we want the ownership to be changed.