This section covers handling input and output in Bash scripts.
In Bash scripting, reading user input is a common task, especially for interactive scripts. The read
command is used for this purpose.
read
Command The basic syntax of the read
command is as follows:
read -p "Enter your name: " username
echo "Hello, $username!"
-p
: Specifies a prompt to display. username
: Variable to store the user input. 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
Bash provides various commands to display output on the screen and redirect it to files.
echo
Command The echo
command is used to print text to the screen:
echo "Hello, World!"
printf
The printf
command allows for more advanced formatting:
name="John"
age=25
printf "Name: %s\nAge: %d\n" "$name" "$age"
Redirecting output to files using >
(overwrite) and >>
(append):
echo "This is a line of text" > output.txt
echo "This is another line" >> output.txt
Reading and displaying the contents of a file:
file_contents=$(<filename.txt)
echo "$file_contents"
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.