Bash Scripting
Considerations
It is crucial that the first line of the Bash script begins with the header
#!/bin/bash
.The extension of a file which represents a script should be
.sh
.Comments in Bash begin with
#
and run to the end of the line:To execute a script, you must be sure your file has the permission to be executed
chmod +x your_script.sh
. Click here to see more about permissions.If you are located in the same PATH were you created the script, you execute your script by running
./your_script.sh
.
Conditionals (Decision Control Structure)
Use conditionals to specify different courses of action to be taken. In this case, we have three possibilities to check a number in a range of other values:
Read more examples about if conditionals.
Loops (Repetitive tasks)
In a loop, commands will continue to run repeatedly until a task is executed for all elements. One useful command for loop calculations is for
. Here is an example of printing numbers from 1 to 9:
If you want to have all the numbers in the same line, add the -n
option. If you want to add 4 units, use double parentheses in the operation:
Click here to see more examples.
Working with files (combining conditionals with Bash commands)
Check the existence of a file to determine the size of the file as well the quantity of words:
📝 It is important to indent the code in the if
block with 4 spaces. Also include 1 space between the contents of the brackets ([
and ]
) and the brackets themselves.
Working with filesystems (combining conditionals with Bash commands)
Send an email if disk usage in the system has reached 90% or more:
You can learn more about Bash scripting by taking a look at this tutorial.
Last updated