Taking User Input in Bash Scripts

Taking User Input in Bash Scripts

Bash scripts are often more useful when they can interact with users. Allowing input provides flexibility. This tutorial will show how to accept user input in bash scripts.

We will cover:

  • Command line arguments - Pass input via the command line

  • Read statement - Prompt for interactive user input

  • Select menus - Give users a list of options

  • Input validation - Sanitize data before use

With these techniques, your bash scripts can respond to user needs. They become customizable and adaptable.

Accepting input allows smarter script behavior. Your programs can make decisions based on values passed in. Or configure operations based on prompted settings.

This tutorial provides the fundamentals for handling input in bash. Let's get started making your scripts more interactive!

Command Line Arguments

The most basic way to get input is through command line arguments when running the script.

For example, save this script as script.sh:

#!/bin/bash

# Print command line arguments
echo "Name: $1"  
echo "Age: $2"

When executed, $1 will contain the first argument, $2 the second, and so on.

Run it like:

./script.sh John 25

This will print:

Name: John
Age: 25

Because we passed "John" as the first argument, it gets populated into $1. "25" goes into $2.

We can also loop through all arguments using $@:

#!/bin/bash

# Loop through arguments  
for arg in "$@"; do
  echo $arg
done

Save and run:

./script.sh John 25 male

This will print each argument on a new line:

John
25 
male

So $@ contains all the command line arguments as individual words we can iterate through.

Read User Input

For interactive input, we use the read builtin:

#!/bin/bash

# Read input
read -p "Enter username: " username
echo "Username is: $username"
  • -p provides a prompt

  • username is the variable to store the input in

When run, this will prompt for a username, then print it back out:

Enter username: john
Username is: john

Whatever the user types as input gets stored in the username variable for use in our script.

We can also read multiple values:

#!/bin/bash

read -p "Enter name and age: " name age
echo "Name: $name, Age: $age"

This allows us to gather multiple interactive values on one line of input.

Menus

Menus are very useful any time you need to provide multiple preset options for users to choose from in your bash scripts.

The select loop displays a menu prompt allowing the user to choose options from a list:

#!/bin/bash

PS3="Choose an option: "

select opt in Start Stop Status Quit; do
  # actions based on choice
done
  • PS3 sets the actual menu prompt text

  • select opt in lists the available options

  • $opt will contain the chosen option

When run, this menu will display:

1) Start
2) Stop
3) Status
4) Quit
Choose an option:

The user can then enter 1, 2, 3, or 4 to choose an option. The chosen value will be stored in $opt.

We can take action based on the choice:

bashCopy codeselect opt in Start Stop; do
  case $opt in
    Start)
      start_program
      ;;

    Stop)
      stop_program
     ;;
  esac
done

If they choose Start, it will call start_program, for Stop it will call stop_program.

The case statement checks the value of $opt and allows us to execute different code blocks based on the menu selection.

This allows the creation of user-friendly menus for scripts with multiple options. We can dynamically control script flow and actions based on the input.

Validate Input

It's important to validate any user input before using it to avoid potential errors:

read -p "Enter age: " age

This reads an age, but the value could be anything entered by the user.

We can validate it is numeric:

if ! [[ $age =~ ^[0-9]+$ ]]; then
  echo "Error: Invalid age"
  exit 1
fi
  • if ! inverts the logic to check for NOT matching

  • [[ ]] provides regular expression matching

  • ^[0-9]+$ regex matches all digits 0-9

This will display an error and exit if non-numeric input is provided.

Some other examples of input validation:

Check a name contains only letters:

if ! [[ $name =~ ^[A-Za-z]+$ ]]; then
  echo "Error: Names can only have letters"
  exit 1
fi

Validate a file exists before using it:

if [ ! -f "$file" ]; then
  echo "Error: File not found"
  exit 1
fi

The -f checks if it's a regular file.

We can also validate the number of arguments:

if [ "$#" -ne 2 ]; then
  echo "Error: 2 arguments required"
  exit 1
fi

$# contains the count of args.

Proper input validation ensures the script fails gracefully with errors rather than executing with invalid data. Important for robust production scripts.

Conclusion

Handling user input is a key skill for writing useful bash scripts. This tutorial covered the core methods for accepting input including command line arguments, read statements, select menus, and input validation. Using input allows your scripts to be dynamic, adaptable, and user-friendly. Scripts can make decisions, retrieve runtime configuration values, and provide different options based on the input. Make sure to validate any input to avoid issues before using it. Mastering user input best practices will level up your bash scripting abilities and enable you to create more powerful automation. Your scripts will be ready for real-world usage by real users.