Bash (short for “Bourne Again SHell”) is a popular command-line shell and scripting language in Unix-like operating systems. Here are some basics of writing Bash scripts:
- Shebang: Start your script with a shebang line to specify the interpreter. For Bash, use
#!/bin/bash
at the beginning of your script. - Comments: Use
#
to add comments to your script. Comments are ignored by the interpreter and are for human readability.
Bash
#!/bin/bash
# This is a comment
- Variables: Declare and assign values to variables without spaces around the equal sign.
Bash
name="John"
age=30
- User Input: Use
read
to get user input.
Bash
echo "Enter your name: "
read username
- Printing: Use
echo
to print output to the console.
Bash
echo "Hello, $name!"
- Conditional Statements: Use
if
,elif
, andfi
for conditional execution.
Bash
if [ $age -ge 18 ]; then
echo "You are an adult."
else
echo "You are a minor."
fi
- Loops: Use
for
andwhile
loops for iteration.
Bash
for i in {1..5}; do
echo "Iteration $i"
done
while [ $age -lt 30 ]; do
age=$((age + 1))
done
- Functions: Define functions using
function
or simply()
.
Bash
function greet() {
echo "Hello, $1!"
}
greet "Alice"
- File Operations: You can use commands like
cat
,mv
,cp
, andrm
for file operations within a script. - Exit Codes: Scripts can return exit codes to indicate success (0) or failure (non-zero).
Bash
if [ $age -lt 18 ]; then
exit 1 # Indicates failure
fi
- Running the Script: Make your script executable with
chmod +x script.sh
and then run it using./script.sh
.
These are some fundamental concepts to get you started with Bash scripting. You can build more complex scripts by combining these elements and using various command-line utilities.
If this was interesting please support me