Scripting and Coding with Bash

8 1 0
                                        

To manage the linux system entirely, you have to master the skill to make simple scripts. Scripts and coding are mostly used to develop apps, but coding is also very useful in automating stuff. Bash is not only used in a interactive console, it is also a entire programming language. All the command are the same, and newlines separate the commands.

1. Syntax

The syntax is exactly the same as in the bash command line, but there are some utilities you have to know. To write something witch is not code (so a comment), you put a # and text. Example: echo test    #This prints test to the output

2. Running with bash (not executable)

Open your favorite text editor and make a file named "test.sh". Here is the content of the file:


echo "Hello Worldy"  #Prints that text

mkdir ThisIsATest #Creates a new directory


Now, save the file and run the following command to run the script:

bash test.sh

That will run our little program until it finishes.

3. Running the program as if bash doesn't exits (executable)

If you don't want to run bash to open the program, use a shebang. Add at the very beginning of the file:

#!/bin/bash

This will make the system recognize what program has to be run to execute the program. In this case it is /bin/bash, which is where the bash program is located.

After editing the file, run this command give the file enough permissions for execution:

sudo chmod +x test.sh

Chmod changes permissions of files. +x Means the file has execution permission now. It may occur you need sudo rights to do this, that's why it's run with sudo.

Finally, to execute the code you can either double-click it in Files or run it from the terminal. In the terminal, when in the same directory as the program, run:

./test.sh

Your program will run and will show the output.

Linux for dummiesWhere stories live. Discover now