BASH Programming Examples
BASH Arrays
Here are the array operations for finding the number of elements, listing elements, etc
#!/bin/bash
STRING=( 'abc', 'ABC', '123' )
echo ${string[@]} # abc, ABC, 123
echo ${string[*]} # abc, ABC, 123
echo ${string[0]} # abc
echo ${string[1]} # ABC
#
echo ${#string[@]} # 3
BASH BANGS
Repeat the last line with (!!)
$ this is a command and parameters $ echo !! this is a command and parameters
Repeat just the parameters if the last command with (!*)
$ this is a command $ echo !* echo is a command is a command
Repeat parameters of the last command with (!!:n and !!:n-m)
$ this is a command $ echo !!:2 echo is is $ this is a command $ echo !!:2-3 echo is a is a
Correct a spelling error with bash substitution
$ eco this is a echo command bash: eco: command not found $ ^co^cho^ echo this is a echo command this is a echo command
Change Directories with bash
To change directories with bash, you will either need to use an alias or a function. A bash script will not work because a child has no control over it's parent. For me, that meant I had to use a function. Here is a simple example:
# Source this function or stick it in
# /etc/profile.d/chdir.sh so it will
# be sourced automatically.
#
# This function scans the chdir line for a valid email address
# and looks up the mailbox if it is. If it's just a dir, this
# function simply changes directories. Typical use is to alias
# cd to chdir: alias cd=chdiro#
function chdir {
EMAIL_FLAG=`echo $1 | awk -F '@' '{print $2}' | awk -F '\.' '{print $2}'`
if [[ -z $EMAIL_FLAG ]]; then
cd $@
return
fi
cd `/bin/dirlookup -u $1`
}