Skip to content
Mahdi Qiamast edited this page Feb 8, 2023 · 5 revisions

Welcome to the Bash-Tricks wiki!

Bash Scripting Tutorial

Quick Access : Creating a Script Shebang Variables Conditional Statements Loops Functions Conclusion

Creating a Script

To create a script, simply open a text editor and save a file with a .sh extension. For example: myscript.sh.

Shebang

The first line of a bash script should always be the shebang: #!/bin/bash. This tells the system which interpreter should be used to run the script.

Variables

In Bash, variables are declared like this: name=value. There is no need to declare the type of the variable.

For example:

name="John Doe"
echo "My name is $name"

Arithmetic Operations

Arithmetic operations can be performed in Bash using double parentheses (( )).

For example:

a=5
b=10
result=$((a + b))
echo "The result is $result

Conditional Statements

Bash supports if statements. The syntax is as follows:

if [ condition ]; then
  # commands
fi

For example:

a=5
if ((a > 0)); then
  echo "a is positive"
fi

Loops

Bash supports for and while loops.

  • for loop can be used to iterate over a range of values or a list of items.

For example:

for i in {1..10}; do
  echo $i
done
  • while loop can be used to repeatedly execute a block of code while a certain condition is true.

For example:

counter=0
while ((counter < 10)); do
  echo $counter
  ((counter++))
done

Functions

Functions in Bash can be declared like this:

function name() {
  # commands
}

For example:

function greet() {
  echo "Hello, $1!"
}

greet "John Doe"

Conclusion

This was a brief introduction to Bash scripting. There is much more to learn and explore, including advanced concepts such as input/output, redirection,process management, andregular expressions`. But with the basics in hand, you should be able to start automating your workflow and taking advantage of the power of the shell.


By Mahdi Qiamast at 2023-02-08 15:55:58 Wednesday