Understand Shell Script
Summary:β
-
- 1.1 Create Example
- 1.2 Write Example
- 1.3 Run Example
- 1.4 Touch Example
-
- 3.1 String Comparison
- 3.2 Numbers Comparison
Goal:β
My intention is to give to you an idea of how you can create your own shell script commands to automate some tasks and show to you some references (https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html) (https://www.shellscript.sh).
Shell script has Variables, Repetition Structures, Conditional Statements and commands UNIX so you can create scripts to use as entrypoint.sh on docker container or just to automate one boring manual task in your S.O.
e.g: This blog is deployed with this Shell Script that generate a build, commit, push to gh-pages branch in my repo.
You can use CLI commands from others softwares installed in your machine, like GIT, Docker, node, npm...
If you understand the power of shell script your imagination will be the limit.
Without further ado...
1. Introductionβ
What is Shell Script?
- A shell script is a text file that contains a sequence of commands for a UNIX-based operating system. It is called a shell script because it combines a sequence of commands, that would otherwise have to be typed into the keyboard one at a time, into a single script.
A Unix shell is both a command interface and a programming language
In our case the computer program is example.sh file
1.1 Create a file called example.sh using terminal, follow:
touch example.sh
chmod +x example.sh
- touch: will create the file
- chmod +x: will give permission to execute file script
You can use touch and chmod commands inside your shell script file too
1.2 Open file example.sh in your preferred IDE
#!/bin/sh
echo "Start" # this command will output in terminal Start string
#!/bin/sh
tells Unix that the file is to be executed by /bin/sh.
1.3 Running file example.sh in terminal
sh example.sh
1.4 Create a new file using shell script
#!/bin/sh
echo "Start"
touch new_file.txt # create new file called new_file.txt
echo "First Line">> new_file.txt # append in new_file.txt the text First Line
2. Variablesβ
A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.
2.1 Declare Variableβ
#!/bin/sh
VARIABLE_MY_NAME="Vinicius"
VARIABLE_TEXT="Hi, my name is "
echo "$VARIABLE_TEXT $VARIABLE_MY_NAME"
Terminal Output:
Hi, my name is Vinicius
2.2 Read Input Variableβ
#!/bin/sh
echo "What is your name?"
read VARIABLE_MY_NAME
VARIABLE_TEXT="Hi,"
echo "$VARIABLE_TEXT $VARIABLE_MY_NAME"
Terminal Output:
What is your name?
> Vinicius
Hi, Vinicius