Categories
Bash Linux

Bash script basics

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:

  1. Shebang: Start your script with a shebang line to specify the interpreter. For Bash, use #!/bin/bash at the beginning of your script.
  2. 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
  1. Variables: Declare and assign values to variables without spaces around the equal sign.
Bash
name="John"
age=30
  1. User Input: Use read to get user input.
Bash
echo "Enter your name: "
read username
  1. Printing: Use echo to print output to the console.
Bash
echo "Hello, $name!"
  1. Conditional Statements: Use if, elif, and fi for conditional execution.
Bash
if [ $age -ge 18 ]; then
    echo "You are an adult."
else
    echo "You are a minor."
fi
  1. Loops: Use for and while loops for iteration.
Bash
for i in {1..5}; do
    echo "Iteration $i"
done

while [ $age -lt 30 ]; do
    age=$((age + 1))
done
  1. Functions: Define functions using function or simply ().
Bash
function greet() {
    echo "Hello, $1!"
}

greet "Alice"
  1. File Operations: You can use commands like cat, mv, cp, and rm for file operations within a script.
  2. 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
  1. 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

Leave a Reply

Your email address will not be published. Required fields are marked *