Bash Primer for Beginners
Written on April 12, 2009 – 4:11 am | by admin
If you are working with OSX or *nix flavored systems and you are not already automating mundane tasks with bash or some other scripting language than you must enjoy repetition. I migrated over to OS X a few years ago and although I had been integrating Linux and Apple Operating Systems into the Windows networks I was running It wasn't until I finally made the switch for personal use that I saw the light. The power of the various *nix command line interpreters and shell scripting environments makes it tough to ever look back. I'll be adding to this primer over time but I'm basically doing it to remind myself to stop wasting my own valuable time on simple repetitive tasks.
Available Libraries: Inside of your bash scripts you have access to anything you can type at the command line regardless of their underlying language. Commands like 'ls' (list all files in a directory) and 'grep' (regular expression parser) are available to you in your scripts.
Where to put your scripts If you define a set of functions in a file you can load them in to your environment at any time by calling 'source script_name' but you will most likely want to source them in your profile configuration (.profile, .bash_profile, or .bashrc) depending on how your environment is configured. You can store a bunch of scripts in one place with any extension you'd like but sh is common (script_to_run.sh) and add that location to your path variable. You can also run a script from within its directory with
./script_to_run.sh param1 param2
Note that you must change the permissions on your script to make it executable.
chmod +x script_name.sh
Shebang Line : Tells the operating system where to find the command interpreter, Make this the first line of your script
#!/bin/bash
Standard Output Send the text 'Hello World' to the screen
echo Hello World
File Output output to file puts the output of the function helloWorld into the file hello.txt the file will be created if it does not exist
helloWorld > hello.txt #overwrite file with output
helloWorld >> hello.txt #append output to file
Variables Standard assignment syntax, prepend with $ to retrieve
#assign like this VAR=5 #access like this $VAR
Functions : Simple function syntax you can pass parameters in to this function and they are available as $1, $2, etc...
function helloWorld(){ #for example 'helloWorld earth' would have the string 'earth' #available witihin the function as $1 }
Pipes '|' : The pipe character will take the output of one operation and pass it in to another. The following line will take the output of the ls command and 'pipe' it into the grep command returning only items in the ls output that match the string 'world'
ls -la | grep world
Tags: bash, system administration