Bash

Bash again? We did this on day one. I know. Hear me out.

Chances are your bash_profile hasn't advanced much since that day - which is a shame. It can be a really useful method for expanding the functionality of your terminal.

Here's some things you might want for reference.

Aliases

If you have programs that you use regularly during web work (for instance, Photoshop or Illustrator for me), expand your alias list.

Aliases take both a name, and a command that they should run, for instance:

alias illus='open -a "Adobe Illustrator" runs illustrator.

I can open any image file by calling illus , which makes my life a lot easier when navigating projects with a lot of image assets. Expanding this list can be a godsend.

Program names are determined by their names in the applications folder.

Note:

You can chain commands in an alias. They can be incredibly powerful tools. for instance alias ~template="mkdir template && cd template && touch index.html" is perfectly valid.


Environment variables

Most of you know this one already, but it bears repeating: In the interests of keeping your API keys hidden when you upload them to Github, you should set your environment variables.

It also means you don't need to remember where you've saved them. Wins all around.

To set environment variables, in your .bash_profile (or other .bash file referenced by your profile):

export YOUR_ENVIRONMENT_VARIABLE='value'

To reference these values within rails, in secrets.yml, you would simply throw YOUR_ENVIRONMENT_VARIABLE in place of your api key values. Magic!

Note:

If you want to know what variables you have access to, and what their values are, you can type ENV in either your terminal, or Pry and see all the variables that have been defined (there are a lot, your system loves ENV variables too).


Functions

Here's where things start getting interesting. On top of just passing variables around and renaming program calls, you can define your own functions, which can do a lot of things for you.

The basic syntax looks sort of similar to javascript:

sayHi () { echo "Hi"; } and they are invoked by just invoking their name:

  sayHi 
    => Hi

While that's nice, it doesn't really do much for us. This is also where the syntax starts to rapidly deviate from what we're used to.

Note: The spacing really matters on these, as do the semicolons for single line blocks.

Functions with arguments

Functions in bash do take and work with parameters, but they're not set where you would expect. Instead, they're numbered, based on the order they are passed to the function.

For instance, a function in JS might look like this:

var howAreYou = function( person, mood ){
    console.log( person + "is " + mood + " today.");
};
howAreYou( "Kane", "awesome" )
    => "Kane is awesome today."

To get the same function, we would actually end up with something like this:

howAreYou () { echo $1" is "$2" today."; }

 howAreYou Kane alright
    => Kane is alright today.

As you can see, we can take as many arguments as we want, and we can be a little less strict about how we structure our strings (at least in this instance).


Conditionals

To make things a little more versatile, it would be nice to be able to work with some conditional statements. As before, they are structured similarly to what you might have seen before in javascript, the syntax is just slightly different.

Because this is going to be our first multi-lined function (for readability's sake), I'm going to migrate it to my .bash_profile.

These functions then become globally available to us, in the terminal. With that said, you will need to close and re-open your terminal windows every time you update the code to see your current version.

greet () { 
    if [ $1 ]
        then
            echo "Hey there, $1."
    else 
            echo "I don't think I know you."
    fi
}

The fi keyword declares the end of our if statement. The closing tags for conditionals is generally the condition reversed, for instance case closes with esac.

We can extend the logic block at the top of the if statement with the operators you'd expect (&&, || etc), along with telling it to look for or folders etc.


Tying this together into something useful

So, we can see there's some utility here. Lets actually look at reducing some of our work load. Every time we set up a new web folder, we follow roughly the same pattern:

mkdir filename cd filename touch index.html mkdir js mkdir css touch js/main.js touch css/style.css atom .

Use emmet to populate our HTML Link our JS Link our CSS ... That's a lot of work. Especially for something you use all the time. Remember: DRY.

The groundwork for this function is incredibly basic:

mks () { 
  mkdir js 
  touch js/main.js 
  mkdir css 
  mkdir css/style.css
  printf "<!DOCTYPE html>
   <html lang=\"en\">
   <head>
     <meta charset=\"UTF-8\">
     <title>Document</title>
     <script src=\"js/main.js\"></script>
     <link rel=\"stylesheet\" href=\"css/style.css\">
     </head>
   <body>
   </body>
   </html>" >> index.html
}

This will immediately generate all our files, it will also print to our html (printf) with everything we need and link our assets. Fancy!

From there, it's a matter of customising it to taste. For instance, the version of this function I use takes some additional steps:

Listens for a parameter Checks if a folder with that name already exists (I don't want to overwrite my data), if it does - don't make anything. If it exists: Create a file named for that parameter If no parameter is provided, populate my current folder with HTML/CSS/JS. If there was, CD into it and populate it. Open the directory with my text editor, and land specifically on the index.html file. Log out all stages of the process so I can tell it's been run. The full task looks like this:

mks () { 
   echo "-------------------------------------"
   if [ -d "$1" ]
    then
    echo "Duplicate filename found. Aborting."
    echo "-------------------------------------"
    return
  fi
  if [ $1 ]
    then
    mkdir $1
    cd $1
    echo $1  "folder has been created."
  fi
  mkdir js 
  touch js/main.js 
  mkdir css 
  mkdir css/style.css
  printf "<!DOCTYPE html>
   <html lang=\"en\">
   <head>
     <meta charset=\"UTF-8\">
     <title>Document</title>
     <script src=\"js/main.js\"></script>
     <link rel=\"stylesheet\" href=\"css/style.css\">
     </head>
   <body>

   </body>
   </html>" >> index.html
   open -a "Sublime Text 2" . index.html
  echo "File generation complete."
  echo "-------------------------------------"
 }

If I wanted to extend this function, I might say:

Automatically curl and link any library I provide. Repeat this task X amount of times to populate a folder full of website templates Fill in some basic CSS I can expect to always use etc, etc, etc.

bonus -- I did extend the function, and it's here.


Sourcing other files

As you expand your list of custom functions , aliases, environment variables, plugins and logs, your bash_profile can become an unwieldy beast pretty quickly.

Ideally it should only hold your aliases and environment variables (unless you're like me and have a lot of them).

Fortunately the solution to this issue is really painless. Make a new file called .bash_scripts or ( whatever you want to call it ) in the root(~) directory. Then go back to your profile and add the line source '.bash_scripts' to the top.

Sorted!


Further reading

Command line cheat sheet 40 tips and tricks for the terminal A giant list of commands which I highly reccomend

results matching ""

    No results matching ""