Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Some useful Bash variables & built-in commands


: > ~/Desktop/create-or-empty-this-file.txt     # cf. help :

type -P cmd             # which alternative; cf. help type
echo $?

type -t cd                # builtin

pwd -P                  # resolve symlinked directories in $PWD path; cf. help pwd


cd                       # cd ~
cd -                     # cd $OLDPWD

alias cdesk="cd ${HOME}/Desktop"
cdesk


echo $_           # last argument of previous command


# re-initialize Bash
exec bash --login


# create a read-only variable and export it
declare -rx cmd=/some/command


# disable file name generation (globbing)
set -f

# match .dot files with wildcard character *
shopt -s dotglob


# kill the last background job
kill $!
kill %-           # Job Control Commands, http://tldp.org/LDP/abs/html/x9134.html


# disable tilde autoexpansion (in ~/.inputrc)
#set expand-tilde off

#_expand()   # in ~/.bashrc
#{
#    return 0;
#}


# ZSH-like preexec & precmd
# http://www.twistedmatrix.com/users/glyph/preexec.bash.txt
# http://glyf.livejournal.com/63106.html
source ~/.preexec.bash    # in ~/.bashrc


line='   string   '
echo "${#line}"     # length
line="${line#"${line%%[![:space:]]*}"}"     # trim leading whitespace, if any
line="${line%"${line##*[![:space:]]}"}"     # trim trailing whitespace, if any
echo "$line"
echo "${#line}"


printf "%b\n" '\041'     # expand backslash escape sequences
printf "%b\n" $'\041'

printf "%q\n" '\041'     # quote the argument
printf "%q\n" $'\041'


/bin/sleep 5 &
echo $!    # process ID of last background command
wait $!    # wait for job completion

while $(/bin/sleep 2); do /bin/date; done


# command path check
IFS=" "
cmdlist=( ls cmd cp  )
IFS=$'\n'
cmds=( $(type -P ${cmdlist[@]}) )
exit_status=$?

if [[ $exit_status -ne 0 ]]; then 
   check_cmds=( ${cmdlist[@]} ${cmds[@]##*/} )
   echo 'No path to the following commands:'
   printf "%s\n" "${check_cmds[@]}" | sort | uniq -u
fi
IFS=$' \t\n'



# read file into array

# version 1

man bash 2>/dev/null | less -p '\$\(< file\)'
OIFS="$IFS"
IFS=$'\n'
set -f    # disable file name generation (globbing)
lines=( $(< "/private/etc/passwd" ) )
set +f
IFS="$OIFS"
printf "%s\n" "${lines[@]}" | nl


# version 2

# preserve empty lines: line =~ ^\n$
/usr/bin/jot -b 'Sample Text' 10 > ~/Desktop/test
unset -v array
declare -a array
declare -i i=0
IFS=$'\777'
IFS=$'\n'
while read -d $'\n' line; do
   #array+="${line}"  # influenced by IFS
   array[i++]="${line}"
#done < <( cat ~/Desktop/test)
done < <( /bin/ed -s ~/Desktop/test <<< $',p' 2>/dev/null)   # also reads last line without final \n
echo "${array[@]}"
echo "${#array[@]}"


# version 3

# use the builtin mapfile to read a file into an array (only Bash 4)
# help mapfile
# http://bash-hackers.org/wiki/doku.php/commands/builtin/mapfile

IFS=$'\777'
/usr/bin/jot -b 'Sample Text' 10 > ~/Desktop/test
mapfile < ~/Desktop/test
mapfile -t < ~/Desktop/test
mapfile -t < ~/Desktop/test myarray
printf "%s\n" "${MAPFILE[@]}"
printf "%s\n" "${MAPFILE[2]}"
for ((i=0; i < "${#MAPFILE[@]}"; i++)); do printf "%s\n" "${MAPFILE[${i}]}"; done
for ((i=0; i < "${#MAPFILE[@]}"; i++)); do printf "%s\n" "${i}:  ${MAPFILE[${i}]}"; done

for ((i=0; i < "${#myarray[@]}"; i++)); do printf "%s\n" "${myarray[${i}]}"; done
for ((i=0; i < "${#myarray[@]}"; i++)); do printf "%s\n" "${i}:  ${myarray[${i}]}"; done

IFS=$' \t\n'


for (( cnt=0; cnt<=100; cnt+=7 )); do
    echo $cnt
done

# Bash 4
for i in {50..100..3}; do
   echo $i
done


# use named classes of characters in regular expressions
man 3 regex 2>/dev/null | less -p 'character class'
man 7 re_format 2>/dev/null | less -p 'character class'
man 3 ctype 2>/dev/null | less -p 'character class'
man 1 grep 2>/dev/null | less -p 'classes  of  characters'
open file:///Library/Documentation/Commands/grep/grep_5.html#SEC8

# example: delete any character except '[:alnum:]', '[:punct:]', and space in array lines
lines=( "${lines[@]//[^[:print:]]/}" )



man bash 2>/dev/null | less -p REPLY       # navigate by pressing n or N
man bash 2>/dev/null | less -p PIPESTATUS
man bash 2>/dev/null | less -p RANDOM
man bash 2>/dev/null | less -p BASH_REMATCH
man bash 2>/dev/null | less -p CDPATH
man bash 2>/dev/null | less -p BASH_SUBSHELL
man bash 2>/dev/null | less -p 'Event Designators'

man bash 2>/dev/null | less -p dotglob
man bash 2>/dev/null | less -p extglob
man bash 2>/dev/null | less -p nocaseglob
man bash 2>/dev/null | less -p nocasematch
man bash 2>/dev/null | less -p nullglob
man bash 2>/dev/null | less -p pipefail


help
help help
help -s cd echo printf pwd type wait
help cd echo printf pwd type wait

help bg fg jobs     # cf. http://commandlinemac.blogspot.com/2008/12/bash-job-control-fg-bg-jobs-and-ctrl-z.html

help umask
umask 077     # protect temp files


help :    
   
#  cf. http://tldp.org/LDP/abs/html/special-chars.html
# the : command does nothing beyond expanding arguments and performing any specified redirections

: ${username=`whoami`}
: ${VAR:=DEF}
: ${HOSTNAME?} ${USER?} ${HOME?} ${MAIL?}
${parameter:?word}     # generate an error if parameter is unset or null by printing word to stdout

: <<-'MULTILINECOMMENT'
...
...
MULTILINECOMMENT

: "$(date)"; echo "$_"
: "$(bash --version)"; echo "$_"


help builtin command

# ignore aliases & functions:
export CLICOLOR_FORCE=1
export LSCOLORS=gxfxcxdxbxegedabagacad     # cyan directories
alias ls='ls -FG'
ls
command ls
command -p ls
\ls   # shortcut


help enable dirs disown hash set shopt ulimit

set -o
shopt -s
shopt -u     


man bash 2>/dev/null | less -p 'PIPESTATUS'
help set | sed -E "s/(pipefail)/$(printf '\e[1m\\1\e[m')/" | less -r

set +o pipefail

ls asx 2>&1 | egrep '.'
echo $?

ls asx 2>&1 | egrep '.'
echo ${PIPESTATUS[*]} 

set -o pipefail

ls asx 2>&1 | egrep '.'
echo $?

ls asx 2>&1 | egrep '.'
echo ${PIPESTATUS[*]} 


# cf. http://codesnippets.joyent.com/posts/show/1630
man bash 2>/dev/null | less -p 'Event Designators'
echo 1 2 3 4 5
echo !^
echo 1 2 3 4 5
echo !$
echo 1 2 3 4 5
echo !:3


# Leopard: readline and vi bindings
# http://www.mrchucho.net/2007/11/06/leopard-readline-and-vi-bindings/

help bind
bind -v
man editrc


# BashTrix, http://distro.ibiblio.org/pub/linux/distributions/amigolinux/download/AmigoProjects/BashTrix/

curl -L -O http://distro.ibiblio.org/pub/linux/distributions/amigolinux/download/AmigoProjects/BashTrix/BashTrix-0.1.tar.bz2

Bind AutoRecovery

Actually it can be any services, but I take Bind(named) under the spot. It's "/etc/init.d/named start" because I'm Fedora user.

#!/bin/sh

PSAW=`ps -o "%p" -C named --no-heading`
PSW=`echo $PSAW | cut -d" " -f 1`

if [ -z "$PSW" ]; then
    echo "Named not running!"
    . /etc/init.d/named start
fi

exit

Generate a bind9 rndc key

// description of your code here

dnssec-keygen -a hmac-md5 -b 256 -n HOST mybrandnewkey


The result will be something like "K%2Ftmp%2Fmybrandnewkey.+157+42885", so you do

cat K%2Ftmp%2Fmybrandnewkey.+157+42885.private


Put the key in /etc/rndc.key like this:
key "rndc-key" {
        algorithm hmac-md5;
        secret "Hr1U28EsMhp8r0TEEjAmksoldReEYuiWwQFH0/gkk6I=";
};

bind9 rndc.conf template

I'm in your /etc, managing your named.

include "/etc/rndc.key";

options {
default-server  127.0.0.1;
default-key     "rndc-key";
};

bind9 google apps zone template

Change 1.2.3.4 for your accelerator's ip and mydomain.net for your domain name

$TTL 86400
@ IN SOA ns1.mydomain.net. hostmaster.mydomain.net. (
                              2007052701      ; serial
                              3H              ; refresh
                              15M             ; retry
                              1W              ; expiry
                              1D )            ; minimum

                    IN NS     ns1.mydomain.net.
                    IN NS     ns1.everydns.net.
                    IN NS     ns2.everydns.net.
                    IN NS     ns3.everydns.net.
                    IN NS     ns4.everydns.net.

@                   IN TXT    "v=spf1 ip4:1.2.3.4 include:gmail.com~all include:mydomain.joyent.net~all ~all"

@                   IN MX   1 aspmx.l.google.com.
@                   IN MX   3 alt1.aspmx.l.google.com.
@                   IN MX   3 alt2.aspmx.l.google.com.
@                   IN MX   5 aspmx2.googlemail.com.
@                   IN MX   5 aspmx3.googlemail.com.
@                   IN MX   5 aspmx4.googlemail.com.
@                   IN MX   5 aspmx5.googlemail.com.

_xmpp-server._tcp   IN SRV  5 0 5269 xmpp-server.l.google.com.
_xmpp-server._tcp   IN SRV 20 0 5269 xmpp-server1.l.google.com.
_xmpp-server._tcp   IN SRV 20 0 5269 xmpp-server2.l.google.com.
_xmpp-server._tcp   IN SRV 20 0 5269 xmpp-server3.l.google.com.
_xmpp-server._tcp   IN SRV 20 0 5269 xmpp-server4.l.google.com.

_jabber._tcp        IN SRV  5 0 5269 xmpp-server.l.google.com.
_jabber._tcp        IN SRV 20 0 5269 xmpp-server1.l.google.com.
_jabber._tcp        IN SRV 20 0 5269 xmpp-server2.l.google.com.
_jabber._tcp        IN SRV 20 0 5269 xmpp-server3.l.google.com.
_jabber._tcp        IN SRV 20 0 5269 xmpp-server4.l.google.com.


@                   IN A      1.2.3.4
www                 IN CNAME  @
mail                IN CNAME  ghs.google.com.
start               IN CNAME  ghs.google.com.
calendar            IN CNAME  ghs.google.com.

bind9 0.0.127.in-addr.arpa template

Refered as /var/named/named.local in my named.conf template

$TTL    86400
@       IN      SOA     localhost. root.localhost.  (
                                      1997022700 ; Serial
                                      28800      ; Refresh
                                      14400      ; Retry
                                      3600000    ; Expire
                                      86400 )    ; Minimum
              IN      NS      localhost.

1       IN      PTR     localhost.

bind9 localhost.zone template

Localhost zone template.

$TTL    86400
$ORIGIN localhost.
@                       1D IN SOA       @ root (
                                        42              ; serial (d. adams)
                                        3H              ; refresh
                                        15M             ; retry
                                        1W              ; expiry
                                        1D )            ; minimum

                        1D IN NS        @
                        1D IN A         127.0.0.1

bind9 named.conf template

Replace 1.2.3.4 with your accelerator's public ip.

acl "internals" { 1.2.3.4 ; 127.0.0/8 ; };
acl "everydns" { 64.158.219.0/24; 4.79.232.0/24; 38.99.14.0/24; 216.218.240.206; 80.84.249.169; 63.219.183.200; };
acl "gandi" { 217.70.177.40; }

options {
        directory "/var/named";
        allow-recursion { "internals"; };
        allow-transfer { "internals"; "everydns"; "gandi";};
        statistics-file "/var/log/named.stats";
        listen-on { 127.0.0.1; 1.2.3.4; };
        forwarders { 208.67.220.220; 208.67.222.222; };
};

include "/etc/rndc.key";

controls {
        inet 127.0.0.1 port 953 allow { 127.0.0.1; } keys { "rndc-key"; };
};

logging {
        channel namedlog {
                file "/var/log/named.log" versions 5 size 2m;
                print-time yes;
                print-category yes;
        };
        category xfer-out { namedlog; };
        category security { namedlog; };
        category lame-servers { null; };
};

zone "." { type hint; file "named.root"; };
zone "0.0.127.in-addr.arpa" { type master; file "named.local"; };
zone "localhost" { type master; file "localhost.zone"; };

zone "mydomain.net" { type master; file "mydomain.net.zone"; };