I'm a front-end developer using a lot of CLI, which runs a few commands to generate a final project or perform tasks. I heard of shell scripting but have never tried it before.
On a daily basis, I use some shell commands from the terminal, like:
cd
: Change the current working directory.ls
: List the files in a directory.pwd
: Print the current working directory.touch
: To create an empty file.grep
Search into a file and display the lines that contain that word.mkdir
: Create a new directory.rm
: Remove a file or directory.cp
: Copy a file.
I decided to get a basic understanding of shell scripting, and the show can be helpful for front-end development tasks.
What is Shell Scripting?
Before starting, what is shell scripting? It helps us to automate tasks or declare things in our shell environment. A shell script is a simple text file that contains shell commands to execute in sequence, and we can use it for:
Automation: Automate repetitive tasks, such as setting up a development environment, running tests, or deploying code.
Environment: Customize your shell environment, like creating aliases for frequently used commands or setting up environment variables to configure our tools.
Build and Deployment: Write a shell script to automate the build and deployment process to simplify it.
Write My First Script
Note: I'm using windows Git for windows comes with bash, so I'm using the terminal bash.
Mac users https://www.howtogeek.com/444596/how-to-change-the-default-shell-to-bash-in-macos-catalina/
In most Linux distributions, the default is bash ;)
We will create our first hello world in the terminal, open the text editor, add the following lines, and save with the name. hello.sh
:
#!/bin/bash
echo "Hello World"
In the first line, we add something called the shebang
line. It specifies the shell interpreter to use, in this case, /bin/bash
, to run the script. First, we must make it executable by running chmod +x hello.sh
, and then run the script by typing ./hello.sh
.
$ ./hello.sh
Hello World
Variables
We can declare a variable to store values in shell scripts and pass values between different commands. For example, we declare a variable version
and assign it the value "1.0". The statement echo
prints the message with the version.
#!/bin/bash
version="1.0"
echo "we are using $version"
Loops
We can use a for
loop to iterate over a list. For example, we have a list of names using the for and do;
#!/bin/bash
version="1.0"
names="dany edgar bezael"
for name in $names; do
echo "Hi $name"
done
Functions
We can define functions to encapsulate complex logic, and our script is easier to maintain using the function
keyword and passing the parameters. It can be accessed within the function using the $n
syntax, where n
is the parameter's position starting from 1.
#!/bin/bash
version="1.0"
names="dany edgar bezael"
function congrats {
echo "hi, how are you $1"
}
for name in $names; do
congrats $name
done
Run the script and see the results:
$ ./hello.sh
hi, how are you dany
hi, how are you edgar
hi, how are you bezael
Read Command Output
Sometimes we want to get the output by one command ls
and perform actions with the output. For those scenarios, we use $(), which is used in bash to perform command substitution and store the result of a command in a variable.
Change the name of the variable names
to files
using $(ls)
to get the file list in the directory.
version="1.0"
##execute the ls command
files=$(ls)
function congrats {
echo "hi, how are you $1"
}
for fileName in $files; do
congrats $fileName
done
Run the script and see the results:
$ ./hello.sh
hi, how are you articles
hi, how are you astro-and-morty
hi, how are you dany.sh
hi, how are you desktop.ini
hi, how are you guide.docx
hi, how are you hello.sh
hi, how are you nba.csv
hi, how are you payments.sh
hi, how are you ~$Qwik.pptx
hi, how are you ~$tpsLocal.docx
The script executes congrats for each file. With the basic overview, we can create a script to do several tasks:
Automate the build process of your front-end project. For example, you can use a script to compile your SASS files, minify your JavaScript files, or copy files from one location to another.
We can use a script to upload your code to a remote server or run a series of tests before deployment.
We can use a script to install the required packages or to start a local development server.
Conditional IF ELSE
After the feedback from Carlos Augusto , add the IF and ELSE section
We can execute a code block in bash shell scripts using the if
statement when the condition is true
, where [condition]
is any valid bash expression that can be evaluated to be either true or false.
We have some options for evaluating conditions like using if:
Equality between two values:
if [ "$value1" = "$value2" ]; then
Inequality between two values:
if [ "$value1" != "$value2" ]; then
If a value is greater than or equal to another value:
if [ "$value1" -ge "$value2" ]; then
If a file exists:
if [ -f "$filename" ]; then
If a directory exists:
if [ -d "$dirname" ]; then
-
If a given string has a length of zero or not
if [ -z $1 ]
.The
if
enclosed with[ ]
and followed by thethen
to indicate the action when the result istrue
, we can use the!
operator to negate the result .
Example:
#!/bin/bash
# assign value to variable 'name'
name="dany"
# check if name have value
if [ -z $name ]; then
echo "Hi $name"
else
# name is empty
echo "Sorry , please set a name"
fi
The script will output "Hi dany" in this example because the name has a value.
Scenario "Scaffolding My Project"
We want to create a script to generate an Angular project with a list of directories and commit the first changes by default.
Let's explain each line:
Create an empty file
scaffold.
sh
with your editorCreate a variable to store the project name
projectName
and read the parameter from the terminal using$1
Use
if [ -z "$1" ]
andexit
to stop the script without parameters (Thanks to Carlos Augusto).Declare another variable for the list of directories "pages components store"
Run the
npx
with theangular/cli
to generate the project using the$projectName
variable.Enter the projectName and src directory using
cd
Print "Generate Directories." using
echo
Use the
for
to iterate the list of directoriesUse the command
mkdir
to create it.When finished, use the git command to initialize the Git and add and commit the changes.
The final code is:
#!/bin/bash
version="1.0"
#validate that the user passed the parameter
if [ -z "$1" ]
then
echo "Please add the parameter to script ex: ./scaffold.sh blog"
exit
fi
#get the project name parameter
projectName=$1
#set a list of directories to create
listOfDirectories="pages components store"
# use the angular cli to generate
npx -p @angular/cli ng new $projectName
cd $projectName
cd src
echo "Generate directories"
#create the list of directories
for directory in $listOfDirectories; do
mkdir $directory
done
# initialize git and commit the changes
git init
git add .
git commit -m "basic template"
Run the project passing the parameter like scaffold.sh
blog
, it generates the angular project with the default directory and commits the changes.
It saves time and helps the company create the same directories structure for a boilerplate.
This example shows how to use shell scripting to automate many other tasks, such as linting code, running tests, or deploying code to a remote server.
Source code:
https://gist.github.com/danywalls/193e46e42751e209760f29c1d3215b51
Next Steps
In conclusion, shell scripting is a powerful tool that can help front-end developers automate tasks and customize their development environment. With a basic understanding of shell scripting concepts, front-end developers can use shell scripts to improve their workflow and make their development process more efficient.
There is much more to learn, including more advanced concepts. You can find more resources online to continue your learning journey.
Top comments (1)
Great post! Well done!
If anyone wants to learn more here is a free open-source eBook: