-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Welcome to the Bash-Tricks wiki!
Quick Access : Creating a Script Shebang Variables Conditional Statements Loops Functions Conclusion
To create a script, simply open a text editor and save a file with a .sh extension. For example: myscript.sh.
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.
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 can be performed in Bash using double parentheses (( ))
.
For example:
a=5
b=10
result=$((a + b))
echo "The result is $result
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
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
in Bash can be declared like this:
function name() {
# commands
}
For example:
function greet() {
echo "Hello, $1!"
}
greet "John Doe"
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 15:55:58 Wednesday