Answers for "linux shell or bash params"

0

linux shell or bash params

# 2.1. Positional Parameters
#-------------------------
# nano userReg-positional-parameter.sh and add the ff:
echo "Username: $1";
echo "Age: $2";
echo "Full Name: $3";

# Now let’s run this script with the three input parameters:
sh userReg-positional-parameter.sh john 25 'John Smith'

# The output will be:
  # Username : john
  # Age: 25
  # Full Name: John Smith
  
  
# 2.2. Flags args
#-------------------------
# nano userReg-flags.sh and add the ff:
while getopts u:a:f: flag
do
    case "${flag}" in
        u) username=${OPTARG};;
        a) age=${OPTARG};;
        f) fullname=${OPTARG};;
    esac
done
echo "Username: $username";
echo "Age: $age";
echo "Full Name: $fullname";

# Let’s run this script with the same input as before, only this time, we’ll add flags to the input:
sh userReg-flags.sh -f 'John Smith' -a 25 -u john

# The output is the same as before, though we have shifted the positions of the username and full name arguments:
  # Username : john
  # Age: 25
  # Full Name: John Smith


# 2.3. Loop Construct - param > array
# nano users-loop.sh and add the ff:
Let’s take an example of the script users-loop.sh, which prints all the usernames that have been passed as input:

i=1;
for user in "$@" 
do
    echo "Username - $i: $user";
    i=$((i + 1));
done

# Now let’s run the script:
sh users-loop.sh john matt bill 'joe wicks' carol

# And we’ll see our output:
  # Username - 1: john
  # Username - 2: matt
  # Username - 3: bill
  # Username - 4: joe wicks
  # Username - 5: carol


# 2.4. Shift Operator - skip Nth
# nb: Shift operator causes indexing to start from the argument at the shifted position.
# nano users-shift-operator.sh and add the ff:
i=1;
j=$#;
while [ $i -le $j ] 
do
    echo "Username - $i: $1";
    i=$((i + 1));
    shift 1;
done

# Let’s run the script with the same input as above:
sh users-shift-operator.sh john matt bill 'joe wicks' carol

# The output will be the same as before:
  # Username - 1: john
  # Username - 2: matt
  # Username - 3: bill
  # Username - 4: joe wicks
  # Username - 5: carol

# In this example, we’re shifting the positional parameter in each iteration by one until we reach the end of the input. Therefore, $1 refers to the next element in the input each time.
Posted by: Guest on October-09-2021

Code answers related to "Shell/Bash"

Browse Popular Code Answers by Language