Bash scripts are an essential tool for automating tasks and processes on a Linux system. They are written in the bash programming language and can be used to perform a wide range of tasks, from simple file operations to complex system administration tasks.
Writing your first script
Here are the steps to write a bash script:
-
Create a new file: You can create a new file using a text editor such as nano or vim. For example, you can create a new file called myscript.sh using the following command: nano myscript.sh.
-
Add the shebang: The first line of a bash script should always start with the shebang, which is a special symbol that tells the system which interpreter to use to run the script. For bash scripts, the shebang is #!/bin/bash.
-
Add commands: The rest of the script will contain the commands you want to run. You can write any bash commands in the script, such as echo, ls, cd, etc.
-
Make the script executable: To make the script executable, you will need to change its permissions using the chmod command. For example, you can use the following command to make the script executable: chmod +x myscript.sh.
-
Run the script: You can run the script by typing its name and executing it. For example, you can run the myscript.sh script using the following command: ./myscript.sh.
Here is an example of a simple bash script that prints the current date and time:
#!/bin/bash
echo "The current date and time are:"
date
You can also pass arguments to a bash script and use them in the script. For example, you can modify the script above to print the current date and time for a specific time zone:
#!/bin/bash
echo "The current date and time in $1 are:"
TZ=$1 date
This is just a basic introduction to writing bash scripts. There is much more you can do with bash scripts, such as using loops, conditional statements, functions, etc. You can also read the bash man page for more information on the bash programming language.
A real script
I found myself doing a lot of repetitive tasks when adding a new blog post. I automated those tasks by creating the script below:
#!/bin/bash
#Author : Olivier Bonnet
echo "Do you want to commit and push your changes ? (y|n)"
read commit
if [ $commit = "y" ]
then
echo "Enter commit message:"
read message
git add .
git commit -m "$message"
git push
else
echo "Not commiting"
fi
echo " "
echo "Upload new version to https://blog.bonneto.ca ? (y|n)"
read answer
if [ $answer = "y" ]
then
echo "Running hugo..."
hugo
echo "------------"
echo "Uploading..."
scp -r ~/Code/hugo/public/. user@domain.com:/destination/folder
else
echo "Upload has been canceled !"
fi
I hope this helps you get started with writing bash scripts. Have fun 🤓