Logo

Bash Scripting Guide - Input/Output

This section covers handling input and output in Bash scripts.

Table of Contents

  1. Reading User Input
    1. Basic read command
    2. Input Validation
  2. Output to Screen and Files
    1. echo Command
    2. formatting with printf
    3. Redirecting Output
    4. Reading from Files
    5. Piping Output

1. Reading User Input

In Bash scripting, reading user input is a common task, especially for interactive scripts. The read command is used for this purpose.

1.1 Basic read Command

The basic syntax of the read command is as follows:


read -p "Enter your name: " username
echo "Hello, $username!"

1.2 Input Validation

Performing basic input validation to ensure the entered data meets specific criteria:


read -p "Enter your age: " age

if [[ "$age" =~ ^[0-9]+$ ]]; then
  echo "You entered a valid age: $age"
else
  echo "Invalid input. Please enter a numeric value."
fi

2. Output to Screen and Files

Bash provides various commands to display output on the screen and redirect it to files.

2.1 echo Command

The echo command is used to print text to the screen:


echo "Hello, World!"

2.2 Formatting with printf

The printf command allows for more advanced formatting:


name="John"
age=25
printf "Name: %s\nAge: %d\n" "$name" "$age"

2.3 Redirecting Output

Redirecting output to files using > (overwrite) and >> (append):


echo "This is a line of text" > output.txt
echo "This is another line" >> output.txt

2.4 Reading from Files

Reading and displaying the contents of a file:


file_contents=$(<filename.txt)
echo "$file_contents"

2.5 Piping Output

Piping output from one command to another:


ls -l | grep ".txt"


Continue to Part 7: File Operations.

Go back to Bash Scripting Guide.

Visit other Developer Guides.