28. Variables and Input/Output in Bash
Scripts become powerful when they can store information (variables) and interact with the user (input/output).
1. Defining and Using Variables
In Bash, variables are defined using the NAME=VALUE syntax (no spaces around the equals sign!). To access the value, use a dollar sign ($).
bash #!/bin/bash
Define variables
GREETING="Hello, Bash user" HOST=$(uname -n) # Command substitution to capture output
echo "$GREETING on device $HOST"
Note on Quoting: Always use double quotes (") when referencing variables, especially if they contain spaces, to prevent word splitting.
2. Output (echo)
We have used echo extensively. It simply prints text or variable contents to the standard output.
3. Taking User Input (read)
The read command prompts the user and stores their input into a specified variable.
bash #!/bin/bash
echo "Please enter your project name:" read PROJECT_NAME
echo "Creating project folder: $PROJECT_NAME" mkdir $PROJECT_NAME
Improved Input: You can combine the prompt and input using the -p (prompt) flag with read:
bash read -p "Enter desired filename: " FILENAME touch $FILENAME