BASH

Bish bosh bash. Why do lots of boring tasks when they could be automated? Bash something out instead.

Why?

A lot of Linux scripts are written in Bash, and an understanding of it helps in other areas, such as piping (|) and outputting (>) in npm scripts.

How?

Using the built in commands as covered in terminal velocity we can start to pull sequences of commands together in one nice little script. It can be more than running sequentially through commands; you can use it with variables, getting user input, loops, sub scripts et al.

A great thing about bash scripts is that they don't have to be compiled, it is right there part of the OS.

To enter bash type bash in the terminal. You'll see something like bash-3.2$.

Then you can run commands directly with bash:

echo hello world

Bash is more useful in a script. Create a file (vim hello) add echo hello world and save as 'hello' (no file extension). Navigate to the directory and run:

bash hello
hello world

Unix has a standard i/o (input output) model consisting of:

  • standard input
  • standard output
  • standard error

Input could be a mouse or something else but it defaults to keyboard. Output could be a printer or something else but it defaults to a console/screen/monitor. Error is like output, it defaults to console/screen/monitor.

These are also streams, and like streams they can be channelled and redirected. To redirect output into a file (using standard output >):

ls -la > listoutputfile.txt

If there is an error, you can write out the error to a file using the standard error output 2>;

ls -la not.here 2> lserror.txt

I used to use the > when backing up a MySQL database without really understanding what it was:

mysqldump --opt -u root -p mydatabase > mbackupfile.sql

To redirect output as input to another script use the pipe |. For example, to get a list of files (recursive) in a directory you can use find and then pipe it into wc which stands for word count:

find . -type f | wc -l

Running scripts

The easiest way to run your script is to run from it's directory using the bash command:

bash ./myscript

If you want your script to be available on your system, you can either add it to the $PATH or you can move it to /usr/local/bin

To turn your script into an executable run:

chmod +x myscript

And run it with:

./myscript

More on Unix permissions can be found at linuxcommand.org.

If you try to run it with just myscript you will get a 'command not found' error. This is because bash will look in the /usr/local/bin for the executable, hence we have to explicitly say that the script is here.

.bashrc refresh/reload

If you edit your .bashrc file and you want to apply those changes without logging off and back on again just run:

. ~/.bashrc

or

source ~/.bashrc

Bash scripting is really powerful. Definitely worth investing some time in it.

References