DEV Community

Cover image for Learn Bash Scripting With Me 🚀 - Day 8
Babs
Babs

Posted on

Learn Bash Scripting With Me 🚀 - Day 8

Day 8 - Positional Parameters

In case you’d like to revisit or catch up on what we covered on Day Seven, here’s the link:

https://dev.to/babsarena/learn-bash-scripting-with-me-day-7-40nc
Enter fullscreen mode Exit fullscreen mode

Positional parameters in Bash scripting are special variables that hold the arguments passed to a script, a function, or a command. They are numerically named: $1, $2, $3, and so on, up to $9. For arguments beyond the ninth, you must use braces, like ${10}, ${11}, etc.

NB- The first argument $0 is owned by the script itself which is when you run the script e.g ./script.sh

You might be confused but it will make more sense as we move on.

SCRIPT

For this lab we want to create a script that will automatically create a user for us.

The script:

#!/bin/bash

echo "Execution of script: $0"
echo "Please enter the name of the new user: $1"

# Adding user command
adduser --home /$1 $1

Enter fullscreen mode Exit fullscreen mode

🔍 Line-by-Line Breakdown

A. Shebang:

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode
  • Tells the system to execute this script with the Bash shell.

B. Script Name Output

echo "Execution of script: $0"
Enter fullscreen mode Exit fullscreen mode
  • $0 is a positional parameter that contains the script’s filename, If you run ./user.sh bob, $0 will be ./user.sh.

C. User Input (via Positional Parameter)

echo "Please enter the name of the new user: $1"
Enter fullscreen mode Exit fullscreen mode
  • $1 is the first argument passed to the script, e.g "./user.sh bob" $1 will be bob.

D. Adding the User

adduser --home /$1 $1
Enter fullscreen mode Exit fullscreen mode
  • Runs the adduser command to create a new user.

--home /$1 → sets the home directory to /$1.

Example: if $1 = bob, home directory becomes /bob.

$1 → the username.

HOW TO RUN THE SCRIPT

  • My script is created and saved as user.sh So if I want to create the user babs, I would run the script with root privilege with the command:
./user.sh babs
Enter fullscreen mode Exit fullscreen mode

Output of the script

The user babs has been successfully created.

🚀 Key Takeaways

$0 → script name

$1 → first argument (the new username)

If you would like to learn more about Bash scripting you can checkout the bash scripting room on TRYHACKME. Link attached below ⬇️

https://tryhackme.com/room/bashscripting
Enter fullscreen mode Exit fullscreen mode

Top comments (0)