Write Bash Script Which Accepts Argument or User Input

There are two ways of writing custom bash script: passing as argument or as input. This time I’ll explain both ways.

Server + Linux

Changing ownership of directories and files. Typing chown -R www-data:www-data * is annoying repetitive task I have to run.

I want a simple version of that command. Like chownership. Or chwn to be even shorter.

The fastest way to do it is by making alias inside .bashrc or .bash_profile

But today I’ll go the other way. Write it in a bash script.

To create a globally available executable bash script, I save the file in /usr/local/bin/. That is for saving even more time rather than typing the full path of the executable.

cd /usr/local/bin/
nano chwn
chmod +x chwn

#1 The First Way: Passing Argument(s)

Bash script executes by typing chwn username. This is the most similar method like the chown’s nature command.

#!/bin/bash

chown -R $1:$1 *

#2 The Other Way: Passing Input(s)

Bash script executes by typing chwn <enter> then the following prompt, asking what user and group I want to apply. Type username <enter>.

This other way uses dual steps. Impractical. Unnatural method as the chown command. I’m not using this. This is more suitable for a program with more complex routines. Like installing multiple packages in a one-go.

#!/bin/bash

echo "user?"
read user
chown -R $user:$user *