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

Welcome to the Bash-Tricks wiki!

Bash Scripting Tutorial

# Hello dear!, I'm Mehdi, I'm glad to see you here.
# In this wiki, I am going to share with you the basics of bash script.
# Join me in this wiki to learn bash
# so that we can write our own bash script and make our work and life easier :)

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, and regular 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 16:21:22 Wednesday