SCRIPT WITH BASH

IN ORDER TO AUTOMATE SOME ACTION

WHAT IS BASH ?

Bash is a command language interpreter. It means it can speak with your computer.

And your computer will understand what you're saying.

We use Bash everyday by typing 'ls', 'cd',...

You can automate command you type every single day through a script.

And that's what we're gonna do.

LET'S SPEAK !

echo Hello, world
cal
history
kill ruby
man bash
cat Gemfile

Have a look at all bash commands you can use

LET'S SCRIPT

TO RUN A BASH SCRIPT

  1. Open a file and save it with .sh (in a Rails app, create a folder named Script where you can save all your scripts)
  2. Add this short line at the beginning of the file :
     
  3. To run it, type :
     
  4. Or make it executable with :

    And then, do :
#!/bin/bash
bash script_file
chmod +x script_file
./script_file

Variables

Argument

Argument is a value you placed just after the command calling your script.

It will be read as $1.

name="Sonia"
echo My name is $name
./script/first_script.sh 32
# in your file :
echo I am $1

You can put all the argument you want separated by a space and then use $1, $2, $3,...

$$$

LOOP

Of course, you can loop in Bash !

If [ condition 1 ]
then
  do that
elif [ conditional 2 ]
then
  do this
else
  do another thing
fi

For example with if

And you can also use for or while.

PRODUCTION DB SCRIPT

RETRIEVE YOUR PROD DB

The idea is to capture your production db and then use it in your development db

It means :

  1. Capture your heroku db
  2. Drop your development db
  3. Recreate it
  4. Restore your db with the heroku captured

DB Capture

Heroku command is :

Retrieve URL

The db capture gives you an url that we'll need for later purpose.

heroku pg:backups capture -a app

Where app is one app in your heroku account.

 

Let's script that.

Heroku command is :

heroku pg:backups public-url -a app

Let's take care of
your development db

And what's good about bash is that you can use postgres command line for example.

dropdb, createdb, pg_restore,...

Retrieve Db Name

Drop&CreateDb

dbname=`grep "development:" -A 1 config/database.yml | tail -n 1 | sed -e "s/.*database: \(.*\)/\1/"`

# in file database.yml grep one line after the word "development"
grep "development:" config/database.yml -A 1 

# just keep one line
tail -n 1

# s = regexp/replacement
# if it matches 'database:', replace with the word corresponding
# to the regexp (.*). \ is just for shell escape
sed -e "s/.*database: \(.*\)/\1/"
dropdb $dbname
createdb $dbname

And... restore your db with your production db using the captured url with cURL

curl $url | pg_restore -d $dbname --no-owner

What is cURL ?

How can you use it ?

Your turn !

You can use script to :

  • give access to collaborators on heroku
  • create and manage admin
  • create app based on your master branch
  • ...
Made with Slides.com