Introduction to Bash Shell Scripting for Frontend Developers
Tags: javascript, bash, scripting
Published: 2023-02-23 18:26:31

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:

1. `cd`: Change the current working directory.
    
2. `ls`: List the files in a directory.
    
3. `pwd`: Print the current working directory.
    
4. `touch`: To create an empty file.
    
5. `grep` Search into a file and display the lines that contain that word.
    
6. `mkdir`: Create a new directory.
    
7. `rm`: Remove a file or directory.
    
8. `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/](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`:

```bash
#!/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`.

```typescript
$ ./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.

```typescript
#!/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;

```bash
#!/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.

```bash
#!/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:

```bash
$ ./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.

```bash
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:

```typescript
$ ./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](https://linktr.ee/sprintwithcarlos) , 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:

1. Equality between two values: `if [ "$value1" = "$value2" ]; then`
    
2. Inequality between two values: `if [ "$value1" != "$value2" ]; then`
    
3. If a value is greater than or equal to another value: `if [ "$value1" -ge "$value2" ]; then`
    
4. If a file exists: `if [ -f "$filename" ]; then`
    
5. If a directory exists: `if [ -d "$dirname" ]; then`
    
6. If a given string has a length of zero or not `if [ -z $1 ]`.
    
      
    The `if` enclosed with `[ ]` and followed by the `then` to indicate the action when the result is `true` , we can use the `!` operator to negate the result .
    

Example:

```bash
#!/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.`](http://scaffold.sh)`sh` with your editor
    
* Create a variable to store the project name `projectName` and read the parameter from the terminal using `$1`
    
* Use `if [ -z "$1" ]` and `exit` to stop the script without parameters (Thanks to [Carlos Augusto](https://linktr.ee/sprintwithcarlos)).
    
* Declare another variable for the list of directories "pages components store"
    
* Run the `npx` with the `angular/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 directories
    
* Use 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:

```bash
#!/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`](http://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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675513894459/718c8cde-6b06-41ee-81ea-3a6ab23cbe64.png align="center")

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](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.