18.01.2020 Views

Working with Linux

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Shell scripting for fun and profit

Pipes and subshells are one way of expanding the capabilities of our shell. The ultimate way is by

writing shell scripts. These scenarios must be taken into consideration when dealing with complex

tasks that can't be automated with a one-line command.

The good news is that almost all the tasks can be automated with the use of shell scripts. We won't go

over an introduction to shell scripts. Instead, we will be looking at some more advanced use cases for

writing them.

Let's start our journey into shell scripting! First thing, let's open a file called script.sh and split the

screen so that we can test while writing. Every shell should start with #!, followed by the interpreter

it uses. This line is called a shebang. We will be using bash as our default interpreter.

It's a good idea to use bash, because it's a common interpreter that comes with most Linux

distributions and also OS X:

#!/bin/bash

Let's start with a simple use case: reading the arguments passed into the command line. We will

assign the value of the first command line argument, $1, to a variable called ARG, and then print it

back to the screen:

ARG=${1}

echo ${ARG}

Let's save our script, assign it execution permissions, and then run it with one argument:

./script.sh test

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!