Showing posts with label Bash. Show all posts
Showing posts with label Bash. Show all posts

Thursday, 19 May 2022

Simple bash stements to set values covering following two scenarios: 1. Set username/password variable if value passed on running the file 2. Or (step 1 doesn't pass values), set them on prompt arguments Create a login.sh file using the below content:
#!/bin/sh

# set -o errexit -o nounset -o xtrace

echo "Initialising Username/Password: "

if test "${1+x}"; then # Set values from inline statement
  username=$1
  password=$2  
else # Otherwise, set values from arguments
  read -p 'Username: ' username
  read -sp 'Password: ' password
fi

echo 'Username: ' $username '| Password: ' $password
1. First scenario, passing the values whilst running the file
$ sh login.sh nepal.user Pokhara123
Username:  nepal.user | Password:  Pokhara123
2. Second scenario, passing the values on prompt arguments
$ sh login.sh 

$ sh login.sh
Initialising Username/Password:
Username: nepal.user
Password: Pokhara123
Username:  nepal.user | Password:  Pokhara123

Thursday, 12 October 2017

Generate Ramdon String on Shell

# Bash function to generate the random alphanumeric string with provided length.
randomString() {
    DEFAULT_LENGTH=6

    # if the parameter is not null, apply new length
    if [ ! -z "$1" -a "$1" != " " ]; then
        LENGTH=$1
    else
        LENGTH=$DEFAULT_LENGTH
    fi
    echo $LENGTH;

    LC_ALL=C tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w $LENGTH | head -n 1
}

Test One:
MyRadomString=$(randomString)
echo "My Radom String: '$MyRadomString'";

# Output:
My Radom String: 'a2d6sd';

Test Two:
MyRadomString=$(randomString 8)
echo "My Radom String2: $MyRadomString";

# Output:
My Radom String2: 'S2sP6sk7';