How to Create and Execute Bash Scripts in Linux


How to Create a Bash Script on Linux

If you want to learn how to write Bash scripts on Linux, all you need is a text editor (and a dash of persistence).

Creating a New File

To get started with scripting, create a new file with the extension ".sh". You can do so easily using the touch command.

touch script.sh

Open the newly created file with any text editor of your choice. It can be a GUI-based editor like Visual Studio Code or a terminal-based one like Vim or nano.

To edit the file with Vim, run the following command:

vim script.sh

Adding Commands

Writing a Bash script is as simple as adding words to a text file. But of course, you need to know which words are valid (interpreted by the command shell), and which aren't.

For the purpose of this guide, let's add the following code to the script, which displays your username and the specified string on execution.

#!/bin/bash
echo $USER
echo "Hello World"

Once you're done with writing the commands, save and exit the file to proceed.

Since a Bash script is a collection of Linux commands, any command you run in the terminal can be included in the script. Some examples include find, grep, man, ls, cd, etc.

How to Execute the Bash Script

Unlike other scripting languages, you don't need to install a compiler (or interpreter) for Bash. Every Linux distro ships with the Bash shell by default, and as a result, has everything you need to execute your scripts.

From the Terminal

The most common way to run Bash scripts is using the terminal. All you have to do is grant execute permissions to the script file using the chmod command.

sudo chmod +x script.sh

Now, to execute the script, run:

./script.sh

The output will display your username and the string "Hello World," as specified in the script file.


Comments

Popular Posts