Run script like command

hello
i have write a script which can create username + password

#!/bin/bash
# Script to add a user to Linux system
if [ $(id -u) -eq 0 ]; then
        read -p "Enter username : " username
        read -s -p "Enter password : " password
        egrep "^$username" /etc/passwd >/dev/null
        if [ $? -eq 0 ]; then
                echo "$username exists!"
                exit 1
        else
                pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
                useradd -m -p $pass $username
                [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
        fi
else
        echo "Only root may add a user to the system"
        exit 2
fi

is it possible to run this script like command (ls mv ...) instead of execute sh script

You can create an alias.

To do this you can use the below command:

alias up='/path/to/the/script.sh'

Then whenever you enter command 'up' (you can change this but I used up to stand for username password) - it will call your script.

If you put the alias in your .profile then it will be set each time you log on.

1 Like

You can make it executable ( chmod +x /path/to/script ) and make sure /path/to is in the PATH variable

1 Like

Yes. Check if a folder called bin exists in your home directory ls ~/bin

If yes, copy/move your script there and ensure it is executable ( chmod +x script )

If ~/bin existed before, you should find it in the PATH variable, ideally as first folder, check this with echo $PATH

If ~/bin didn't exist before, create it manually mkdir ~/bin , copy/move your script there and again ensure it is executable. Now start another shell/terminal, BASH will read a file called .profile and from now on always add ~/bin to the PATH variable.

When everything is done, you will be able to call your script by just typing script , from anywhere.

If you have more executable scripts, just copy them there and start using them immediately without further actions.

1 Like