Syntax Fundamentals
Syntax fundamentals in Bash (Bourne-Again Shell) refer to the essential rules and structures that govern how commands and scripts are written in the Bash shell environment. These rules dictate how the shell interpreter processes commands, providing the foundation for scripting and automation in Unix/Linux systems. Mastering Bash syntax is essential for system administrators, developers, and users who need to efficiently manage system resources and automate tasks.
Basic Command Structure
The most fundamental aspect of Bash syntax is its command structure. Commands in Bash typically follow this pattern:
command [OPTIONS] arguments
Here, the command is executed with optional parameters (OPTIONS) that modify its behavior, followed by the arguments the command will operate on.
Example:
ls -la /home/user
In this example, ls
is the command, -la
are options (list in long format and show hidden files), and /home/user
is the argument specifying which directory to list.
Variables and Assignments
Variables in Bash allow you to store and reference data throughout your script. Variable assignment follows this syntax:
variable_name=value
Note: There should be no spaces around the equals sign in Bash variable assignments.
To access a variable’s value, prefix the variable name with a $
:
name="John"echo "Hello, $name!"
This outputs: Hello, John!
Variables can store strings, numbers, or the output of commands using command substitution:
current_date=$(date)echo "Today is $current_date"
Quoting and Escaping
Bash offers several ways to handle text that contains special characters:
Double Quotes (
"
): Preserve variable expansion but interpret special characters.message="Hello, $USER"echo "$message" # Outputs: Hello, usernameSingle Quotes (
'
): Preserve text exactly as written, no variable expansion.message='Hello, $USER'echo "$message" # Outputs: Hello, $USEREscape Character (
\
): Escape a single character to remove its special meaning.echo "The price is \$5.00" # Outputs: The price is $5.00
Operators
Bash supports various types of operators:
Arithmetic Operators
Used for mathematical operations in Bash:
result=$((5 + 3)) # Additionecho $result # Outputs: 8result=$((10 - 2)) # Subtractionecho $result # Outputs: 8result=$((4 * 3)) # Multiplicationecho $result # Outputs: 12result=$((15 / 3)) # Divisionecho $result # Outputs: 5result=$((20 % 3)) # Modulus (remainder)echo $result # Outputs: 2
Logical Operators
Used in conditional expressions:
# AND operator: both conditions must be trueif [ "$age" -gt 18 ] && [ "$registered" = true ]; thenecho "Eligible to vote"fi# OR operator: at least one condition must be trueif [ "$age" -gt 65 ] || [ "$disabled" = true ]; thenecho "Eligible for assistance"fi# NOT operator: inverts the conditionif ! [ -f "$file" ]; thenecho "File does not exist"fi
Comparison Operators
Used for comparing values:
For numeric comparisons:
-eq
: Equal to-ne
: Not equal to-gt
: Greater than-lt
: Less than-ge
: Greater than or equal to-le
: Less than or equal to
For string comparisons:
=
or==
: Equal to!=
: Not equal to-z
: String is empty-n
: String is not empty
Example:
if [ "$count" -gt 100 ]; thenecho "Count exceeds limit"fiif [ "$name" = "John" ]; thenecho "Hello John!"fi
Conditionals
Conditionals allow scripts to make decisions based on specific conditions.
If-Else Statement
if [ condition ]; then
# Commands to execute when condition is true
elif [ another_condition ]; then
# Commands to execute when another_condition is true
else
# Commands to execute when all conditions are false
fi
Example:
This code checks the age and prints whether the person is a minor, adult, or senior:
#!/bin/bashage=25if [ $age -lt 18 ]; thenecho "Minor"elif [ $age -ge 18 ] && [ $age -lt 65 ]; thenecho "Adult"elseecho "Senior"fi
Loops
Loops enable repeated execution of commands based on specified conditions.
For Loop
for variable in list; do
# Commands to execute for each item in the list
done
Example:
The example here iterates through a list of fruits and prints each one:
#!/bin/bashfor fruit in apple banana orange; doecho "I like $fruit"done
While Loop
while [ condition ]; do
# Commands to execute while condition is true
done
Example:
The example increments a counter from 1 to 5 while printing its value:
#!/bin/bashcounter=1while [ $counter -le 5 ]; doecho "Count: $counter"((counter++))done
Until Loop
until [ condition ]; do
# Commands to execute until condition becomes true
done
Example:
This example increments a counter from 1 to 5, stopping when the condition becomes true:
#!/bin/bashcounter=1until [ $counter -gt 5 ]; doecho "Count: $counter"((counter++))done
Functions
Functions allow you to group commands for reuse throughout your script.
function_name() {
# Commands to execute
# Optional return value
return value
}
Or the alternative syntax:
function function_name {
# Commands to execute
}
Functions are called simply by using their name.
Example:
The function prints a greeting message using an argument:
#!/bin/bash# Define the functiongreet() {echo "Hello, $1!"return 0}# Call the function with argumentgreet "World"
Functions can take arguments, accessed within the function as $1
, $2
, etc., and return values using the return
statement (limited to integers 0-255, typically used for status codes).
These were some of the fundamental concepts of Bash syntax to help you get started. Learn more about Bash with the Bash courses on Codecademy.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Command Line on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn the Command Line
Learn about the command line, starting with navigating and manipulating the file system, and ending with redirection and configuring the environment.With CertificateBeginner Friendly4 hours