Similar to other languages, we can use conditions, loops, and other constructs when writing our scripts that help us solve more complex problems.
Every command that can be executed on the CLI, like
ls we already learned about and even pipes and chaining, can also be used in bash scripts.
Declaring variables in bash is very straightforward, as we can simply assign a value to every not-reserved word like below.
To use our variable, we can prepend a
$ to the variable name.
To compare the just declared variable in a condition, we can use it like above and evaluate its value in an if statement like this:
Whenever we want to run operations on multiple files, or just need multiple executions, we can make use of loops. Here are the three most commonly used loops in Bash.
Just like in other languages (and on the CLI) we can make use of conditional operators
|| as OR and
&& as AND to evaluate
and chain conditions.
To structure our scripts a little more, let's take a look at bash functions. They help us with putting different parts and tasks of our script into coherent blocks that can be invoked multiple times and with different arguments. Here's how a basic function looks like in bash
The example above shows us that we can execute functions or statements by calling /evaluating them like this
$(<function name>) and we'll be able to receive the returned value.
Unlike other programming languages, bash doesn't have a real
return statement, but functions instead return the status of the last executed statement inside the function.
If we don't need a return value however it is enough to simply call the function by its name. In the example above, simply calling
say without any braces would output
' world' because
we're not passing a parameter.
As shown above, every argument we pass into a function can automatically be accessed by
$n, corresponding to the position of the parameter
in the function's invocation. There are a few extra variables that are automatically defined for us
$0is automatically assigned (reserved) the function’s name
$#automatically holds the number of passed parameters
$@hold all passed parameters and can be iterated over
As mentioned above there is no real
return statement for functions, like we know from other languages. Instead, bash reserves the
return keyword for what's commonly referred to as status codes or a function's exit status.
The return value of any function execution is automatically assigned to the variable
$?, right after running the function or command.
This behavior is the same for any command we run, as they all have status/exit codes. So running a successful
ls command would
$? the value
0 — It is defined that
0 is a successful execution and 1 - 255 are reserved for errors.