Data Migration Shell Script Example

A nice little script written around the rsync command used to successfully migrate large amounts of data between NFS filesystems, avoiding .snapshot folders in the process.  A simple script in essence but a nice reference example nonetheless on the use of variables, functions, if statements, case statements, patterns and some useful commands, e.g. using sed to remove whitespace at the front of a variable returned by wc.

A simple but proper shell script that can almost certainly be built/improved upon using tee to write std output to a log file as well as the screen for instance, and using find to subsequently count the number of files afterwards because df is unlikely match to the nearest megabyte across different filesystems served by different NAS’s for comparison/verification.

#!/usr/bin/bash

#Generic script for migrating file systems.
#Variables Section
  SOURCE=$1
  DEST=$2

#Functions section
  function migratenonhiddenfolders(){

    echo “Re-Synchronising non-hidden top level folders only…”

  #Synchronise the data
    ls -l $SOURCE | grep ^d | awk {‘print $9’} | while read EACHDIR; do
      echo “Syncing ${SOURCE}/${EACHDIR} with ${DEST}/${EACHDIR}”
      timex /usr/local/bin/rsync -au ${SOURCE}/${EACHDIR}/* ${DEST}/${EACHDIR}
  done
  }

#Code section
  if [[ -z $1 ]];then
    echo “No Source or Destination specified”
    echo “Usage: migrate.sh /<source_fs> /<destination_fs>”
    exit
  fi
  if [[ -z $2 ]];then
    echo “No Destination specified”
    echo “Usage: migrate.sh /source_fs> /<destination_fs>”
    exit
  fi

#Source and Destination filesystems have been specified
  echo “Source filesystem: $SOURCE”
  FOLDERCOUNT=`ls -l $SOURCE | grep ^d | wc -l | sed -e ‘s/^[ \t]*//’`
  echo “The $FOLDERCOUNT source folders are…”
  ls -l $SOURCE | grep ^d | awk {‘print $9’}
  echo
  echo “Destination filesystem: $DEST”
  echo
  echo -n “Please confirm the details are correct [Yes/No] > “
  read CONFIRM
    case $CONFIRM in
        [Yy] | [Yy][Ee][Ss])
          migratenonhiddenfolders
          ;;

       *)
        echo
        echo “User aborted.”
        exit
       ;;
    esac

#Clean exit
exit

Improved version (with logging) shown below.

#!/usr/bin/bash

#Generic script for migrating file systems.
#Variables Section
  SOURCE=$1
  DEST=$2

#Functions section
  function migratenonhiddenfolders(){

    echo “Migrating ${SOURCE} to ${DEST} at `date`” >> ~/migration.log
    echo “Re-Synchronising non-hidden top level folders only…” | tee -a ~/migration.log
    #Synchronise the data
    ls -l $SOURCE | grep ^d | awk {‘print $9’} | while read EACHDIR; do
    echo “Syncing ${SOURCE}/${EACHDIR} with ${DEST}/${EACHDIR} at `date`” | tee -a ~/${DEST}_${EACHDIR}.log ~/${DEST}.log ~/migration.log
    timex /usr/local/bin/rsync -au ${SOURCE}/${EACHDIR}/* ${DEST}/${EACHDIR} | tee -a ~/${DEST}_${EACHDIR}.log ~/${DEST}.log ~/migration.log
    echo “Completed migrating to ${DEST}/${EACHDIR} at `date`” | tee -a ~/${DEST}_${EACHDIR}.log ~/${DEST}.log ~/migration.log
    done
  }

#Code section
  if [[ -z $1 ]];then
    echo “No Source or Destination specified”
    echo “Usage: migrate.sh /<source_fs> /<destination_fs>”
    exit
  fi
  if [[ -z $2 ]];then
    echo “No Destination specified”
    echo “Usage: migrate.sh /source_fs> /<destination_fs>”
    exit
  fi

#Source and Destination filesystems have been specified
  echo “Source filesystem: $SOURCE”
  FOLDERCOUNT=`ls -l $SOURCE | grep ^d | wc -l | sed -e ‘s/^[ \t]*//’`
  echo “The $FOLDERCOUNT source folders are…”
  ls -l $SOURCE | grep ^d | awk {‘print $9’}
  echo
  echo “Destination filesystem: $DEST”
  echo
  echo -n “Please confirm the details are correct [Yes/No] > “
  read CONFIRM
  case $CONFIRM in
    [Yy] | [Yy][Ee][Ss])
      migratenonhiddenfolders
     ;;
  *)
      echo
      echo “User aborted.”
      exit
      ;;
  esac

#Clean exit
  exit

###########################################################
##
## Data Migration script by M.D.Bradley, Cyberfella Ltd
## http://www.cyberfella.co.uk/2013/08/09/data-migration/
##
## Version 1.0 9th August 2013
###########################################################

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Trimming whitespace off the beginning of a variable in bash

Sometimes a variable can be returned with a few empty (whitespace) characters in front of it.  This is not too much of an issue when running individual commands ending in a | wc -l to count the number of lines, but when you want to sandwich the variable in between two words in a more meaningful echo statement in a script, that “gap” between the words and the numbers looks untidy.  To remove the preceeding whitespace, append the following into the command used to build the variable (between the back ticks `   `).

     sed -e ‘s/^[ \t]*//’

e.g. to count the number of folders…

     FOLDERCOUNT=`ls -l $SOURCE | grep ^d | wc -l | sed -e ‘s/^[ \t]*//’`

     echo “The $FOLDERCOUNT source folders are…”

Will output this…

     The 4 source folders are…

instead of this…

     The            4 source folders are…

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Translate text from lowercase to uppercase

When comparing files on Linux, there are a bunch of tools available to you, which are covered in separate posts on my blog.  This neat trick deserves its own post though -namely converting between upper and lowercase.

Before comparing two text files that have been sorted, duplicates removed with uniq and grepped etc, remember to convert to lower or upper case prior to making final comparison with another file.

tr ‘[:lower:]’ ‘[:upper:]’ <input-file > output-file

My preferred way to compare files isn’t using diff or comm but to use grep…  More often than not it gives me the result I want.

grep -Fxv -f first-file second-file

This returns lines in the second file that are not in the first file.

When comparing files, remember to remove any BLANK LINES.

 

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Comparing two lists in Linux/UNIX

Deserves its own blog post this one.  A new favourite of mine, that seems more reliable than using diff or comm on account of its being easy to understand, and thus less likely to get wrong (matter of opinion).

grep -Fxv -f masterlist backupclients which would list any lines in a list of backupclients that were not found in the master list.

Note:  This lists any lines in the second file that are not matched in the first file (not the other way around).

-F pattern to match is a list of fixed strings

-x select only matches that match the whole line

-v reverses it, i.e. does not match the whole line

-f list of strings to (not) match are in this file

Result: filename output entire lines from the file specified that are not in the file specified by –f

 

It can be useful to convert all text to UPPERCASE and don’t forget to REMOVE EMPTY LINES in files.

Text can be converted to uppercase with tr ‘[:lower:] [:upper:]’ <infile >outfile

If you want to list only the lines that appear in two files, then comm -12 firstfile secondfile works well.

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Manipulating Files in Linux

RHCE 2: Manipulating files in Linux.  The following blog post is a concise summary of how one can interact with files on a Linux system.  In fact the information contained herein applies to all Linux and UNIX.  By my own admission, if you learn everything contained in this one post of the many posts on my blog, you’ll be well on your way when it comes to turning your hand to any UNIX or Linux system.  Basic but essential knowledge.

Creating a file

“Everything is a file”.  You’ll hear that said about UNIX and/or Linux.  Unlike Windows, there is no registry, just the filesystem.  As such, everything is represented by a file somewhere in the filesystem.  More on the different types of file later.

cat, touch, vi, vim, nano, tee and > (after a command) are all used to create files.    tee is special since when you pipe a command into tee, it will write standard input to standard output as well as displaying the results on screen (using > would hide output to the screen as it redirects it to a file instead).

Listing files

ls, ll, ll -i (displays inode of the file) commands are used with many possible switches to display directory listings.  e.g. ls -al (long listing showing permissions, including hidden files)  ls -lart (same but sorted in reverse date order too) are common uses of the ls command.

Display contents of a file

cat, more, less, head, tail, view, vi, vim, nano, uniq and strings are all commands used to display files in similar but slightly different ways, i.e. in their entirety, a page at a time, the top lines, the bottom lines, in an editor, just unique lines of the file and just ascii text (not binary information) contained within a file.

Copy or Rename a file

cp, rsync, tar, cpio, mv   -can all be used to copy files, move files or rename files.  In Linux, you don’t rename a file, you move it.

Remove a file

rm, erase, rmdir (if it’s a directory, though rm -r will recurse through the tree removing subdirectories as well as files contained beneath the specified starting point.  This is dangerous, especially when used with rm -rf to force it.)

Ownership and Permissions

Like Windows, files have an owning user, they also have an owning group attribute as well as permissions that dictate what level of access the owning user, owning group and everyone else has to the file (or directory).  This is slightly different to Windows, whereby permissions can be set on multiple groups added to the ACL (access control list) of a file (or directory) and takes some getting used to.

To change owner or group use the chown and chgrp commands, or just the chown user:group command to do both in one go.

To change the permissions, use the chmod command.

-rwxrwxrwx    where – means regular file (more on different file types later), then the first rwx is read, write, execute permissions of the owner, the second rwx is the same for the group and the third rwx is everyone else.  Each permission bit has a value

– 421 421 421

So to set permissions of owner full access, group read, everyone read i.e. rwxr–r– would be 4+2+1, 4, 4 i.e. 744 so chmod 744 filenameFull access for everyone would be chmod 777 filename.

Types of file

Regular   (ascii or binary)

Executable   (allowed to execute)

Directory   (contains one or more files)

Symlink   (hard or soft link to another file – hard has it’s own inode but is still linked, soft shares the inode of the linked file.  ln -s realfile linkfile is a common use.  It’s common to get the order the wrong way around.)

Device   (character/raw or block special files are used to send streams of data to kernel modules which controls the sending of the data stream to hardware, e.g. a volume group has a character special file, a disk device has a block special file)

Named Pipe (fifo – first in first out used to send one-way streams of data to other processes (inter-process communication or IPC).

Socket    -a two-way named pipe.  Used for system services for example, whereby information is received and transmitted.

File attributes

Besides permissions that control access to a file, files on a Linux system can also have attributes applied to them that controls what can and can’t be done to the file – even by the root user.

stat   -Display statistics about a file.

wc    -Word count a file (can also be used with wc -l to count lines in a file, or wc -c to count characters)

lsattr    -List attributes of a file.

chattr     -Change attributes of a file.

a   -Can only be appended to

A   -Access time not updated

c    -Auto compress

d    -cannot be backed up by the dump command

D   -contents of the directory are written synchronously to disk

i    -is immutable (cannot be changed or deleted)

j    -is added to the journal before being written to disk on journalling file systems

s    -is securely deleted, i.e. actual data blocks are wiped too

S   -file is synchronously written to disk

u   -undeletable

Pattern matching

The famous grep command is used to simply match lines of text contained in a file, or more cleverly lines containing patterns of text (defined by regular expressions) in a file or files.  More on Regular Expressions will be covered later.

grep -l pattern file1 file2 file3   -finds lines containing pattern in files file1, file2 and file3

grep -n pattern file1    -find the pattern and displays the line numbers where the matches occur.

grep -v     -anything but the pattern matches

grep ^pattern   or    grep pattern$  matches the patterns when they occur at the beginning or the end of the line only.

grep -i   ignores case (because Linux is case sensitive of course)

egrep or grep -E ‘pattern1|pattern2’ file1    -displays either pattern matched

Comparing files

diff, comm and grep are used to compare two files and print matching lines and differing lines, e.g. diff -c file1 file2   displays the output in 3 sections.   comm 123 file1 file2 very similar to diff -c whereby section 1, 2 and/or 3 are suppressed instead of displayed.  Section 1 contains lines unique to file1, section2 contains lines unique to file2 and section3 contains lines in both.  Use of comm takes some getting used to, so read the man page to be sure you’re getting the results you’re after and not something else, or just use diff -c.  comm is very cool tool though, and I find myself using it more than diff.  A new favourite is grep -Fxv -f decommissioned backupclients which would list any lines in a list of backupclients that were not found in the decommissioned list.

Finding files

The find command in UNIX/Linux is fantastic, but like Linux itself, it has a reputation for having a steep learning curve.  I’ll try to make it easy by keeping this short and sweet.

find path option action   where option and action have values and commands specifed respectively, i.e. find path option value action command

e.g. find ./ -size -1G -exec ls -al {} \;     find     ./      -size -1G      -exec ls -al {} \;   will find files from the present working directory down that are less than 1Gb and will long list any matches

other options are

-name     match names (can also use regular expressions like grep)

-atime     last accessed time

-user       owning user is

-mtime    last modified time

-ctime     change time

-group     owning group

-perm     permissions are e.g. 744

-inum     inode number is

-exec can be replaced with -ok or -print to keep the command simpler for simpler finding requirements.  -exec can execute any command upon the files found that match the specified matched conditions, e.g. ls, cp, mv or rm (very dangerous).

the locate command can also be used to find files.  for executable binary commands, it might be quicker to use which or whereis to display the path of the binary that would be executed if the full path was not specified (relying upon the PATH environment variable to locate and prioritise.  Also check for any command aliases in your ~/.profile and ~/.bashrc if whereis or which turns nothing up as a command alias by one name may be calling a binary by another name.  I begin to digress!

Sorting files

sort

sort -k2 -n    -sort on column 2, numerically (useful if the file contains columns of data).  Can also be used to sort by month, e.g. ls -al | sort -k 6M  and use -o outputfile to write results to a file rather than > or >>

Extracting data from a file

cut and awk can be used to extract delimited lines of data from a file or columns of data from a file respectively, e.g.

cat filename | cut -d, -f3 filename     -displays the third key in a comma delimited file

cat filename | awk {‘print $3’}    -displays the third column in a file

Translating data in a file

sed and tr are stream editors for filtering and transforming text and translating or deleting characters respectively.  many great examples of sed are to be found on the internet.

a simple example of sed would be echo day | sed s/day/night/ to convert all occurrences of the word day into night.

a similar, simple example of tr would be tr “day” “night” < input.txt > output.txt

 

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

List UIDs of failed files

If you’re copying data from an NFS device, the local root user of your NFS client will not have omnipotent access over the data, and so if the permissions are set with everyone noaccess, i.e. r-wr-w— or similar (ending in — instead of r–) then even root will fail to copy some files.

To capture the outstanding files after the initial rsync run as root, you’ll need to determine the UID of the owner(s) of the failed files, create dummy users for those uids and perform subsequent rsync’s su’d to those dummy users.  You won’t get read access any other way.

The following shell script will take a look at the log file of failures generated by rysnc -au /src/* /dest/ 2> rsynclog and list uid’s of user accounts that have read access to the failed-to-copy data.  (Note: when using rsync, appending a * will effectively miss .hidden files.  Lose the * and use trailing slashes to capture all files including hidden files and directories).

subsequent rsync operations can be run by each of these users in turn to catch the failed data.  This requires the users to be created on the system performing the copy, e.g. useradd -o -u<UID> -g0 -d/home/dummyuser -s/bin/bash dummyuser

This could also easily be incorporated into the script of course.

#!/usr/bin/bash

#Variables Section

    SRC=”/source_dir”
    DEST=”/destination_dir”
    LOGFILE=”/tmp/rsynclog”
    RSYNCCOMMAND=”/usr/local/bin/rsync -au ${SRC}/* ${DEST} 2> ${LOGFILE}”
    FAILEDDIRLOG=”/tmp/faileddirectorieslog”
    FAILEDFILELOG=”/tmp/failedfileslog”
    UIDLISTLOG=”/tmp/uidlistlog”
    UNIQUEUIDS=”/tmp/uniqueuids”

#Code Section

    #Create a secondary list of all the failed directories
    grep -i opendir ${LOGFILE} | grep -i failed ${LOGFILE} | cut -d\” -f2 > ${FAILEDDIRLOG}

    #Create a secondary list of all the failed files
    grep -i “send_files failed” ${LOGFILE} | cut -d\” -f2 > ${FAILEDFILELOG}

    #You cannot determine the UID of the owner of a directory, but you can for a file
    
    #Remove any existing UID list log file prior to writing a new one
    if [ -f ${UIDLISTLOG} ]; then
        rm ${UIDLISTLOG}
    fi

    #Create a list of UID’s for failed file copies    
    cat ${FAILEDFILELOG} | while read EACHFILE; do
        ls -al ${EACHFILE} | awk {‘print $3’} >> ${UIDLISTLOG}
    done

    #Sort and remove duplicates from the list
    cat ${UIDLISTLOG} | sort | uniq > ${UNIQUEUIDS}    

    cat ${UNIQUEUIDS}

exit

Don’t forget to chmod +x a script before executing it on a Linux/UNIX system.

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Counting number of files in a Linux/UNIX filesystem

cd to the starting directory, then to count how many files and folders exist beneath,

find . -depth | wc -l

although in practice find . | wc -l works just as well leaving off -depth.  Or to just count the number of files

find . -type f | wc -l

Note that on Linux, a better way to compare source and destination directories, might be to count the inodes used by either filesystem.

df -i

Exclude a hidden directory from the file count, e.g. .snapshots directory on a NetApp filer

#find ./ -type f \( ! -name “.snapshot” -prune \) -print | wc -l – Note:  had real trouble with this!

New approach…  :o(

ls -al | grep ^d | awk {‘print $9’} | grep -v “^\.” | while read eachdirectory; do

     find ./ -depth | wc -l

done

Then add up numbers at the end.

Another way to count files in a large filesystem is to ask the backup software.  If you use emc Networker, the following example may prove useful.

sudo mminfo -ot -q ‘client=mynas,level=full,savetime<7 days ago’ -r ‘name,nfiles’

name                         nfiles

/my-large-volume          894084

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Customising your bash prompt and titlebar

It still surprises me how many servers I log on to that don’t have friendly prompts.  It strikes me as being downright dangerous in the right hands, let alone the wrong ones.

Solaris defaults to csh, HP-UX to ksh and Linux to bash.  Despite having “grown up” on Korn, I much prefer the intuitiveness of bash (command recall using arrow keys!) and would highly recommend all UNIX sysadmins install it.  One word of caution though – If you configure your user account to use bash as it’s default shell, then make sure you have some way into the system in the event that a customisation of your bash configuration goes awry.  HP-UX has a convenient backdoor by means of it’s Service Processor, but you may not be so lucky, subsequently shutting yourself out of your system.  Logging on as root may not be an option for you is local root logins or log in as root over ssh is disabled (common practice in these times of heightened security).  Lastly, don’t change the root users default shell in /etc/passwd.  Stick with the unmodified OS defaults set by the vendor.

OK, with the pitfalls and warnings out of the way, lets customise our bash prompt.  When bash is invoked (either by typing bash at the command prompt, or by your /etc/passwd entry for your user account), the /etc/bashrc file is read to set things up.  I’d not recommend modifying the /etc/bashrc file.  If you want to make customisations that apply only to yourself, then create a .bashrc file in your home directory and play in there.  Don’t forget to chmod +x the file afterwards if you want it to work.

Mine reads as follows

#!/bin/sh

PS1=”\u@\h \w $ “

clear

MYNAM=`grep ${USER} /etc/passwd | cut -d: -f5 | awk {‘print $1’}`

HOSTNAM=`hostname | cut -d. -f1`

echo “${MYNAM}, you are connected to ${HOSTNAM}”

exit

It sets an informative PS1 variable so that the prompt displays my username ‘at’ hostname followed by the present working directory with the obligatory $ prompt on the end.  This is all I need I find, but there are other things you can add if you choose.

\a : an ASCII bell character (07)
\d : the date in “Weekday Month Date” format (e.g., “Tue May 26”)
\D{format} : the format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required
\e : an ASCII escape character (033)
\h : the hostname up to the first ‘.’
\H : the hostname
\j : the number of jobs currently managed by the shell
\l : the basename of the shell’s terminal device name
\n : newline
\r : carriage return
\s : the name of the shell, the basename of $0 (the portion following the final slash)
\t : the current time in 24-hour HH:MM:SS format
\T : the current time in 12-hour HH:MM:SS format
\@ : the current time in 12-hour am/pm format
\A : the current time in 24-hour HH:MM format
\u : the username of the current user
\v : the version of bash (e.g., 2.00)
\V : the release of bash, version + patch level (e.g., 2.00.0)
\w : the current working directory, with $HOME abbreviated with a tilde
\W : the basename of the current working directory, with $HOME abbreviated with a tilde
\! : the history number of this command
\# : the command number of this command
\$ : if the effective UID is 0, a #, otherwise a $
\nnn : the character corresponding to the octal number nnn
\\ : a backslash
\[ : begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
\] : end a sequence of non-printing characters

The remainder of my custom .bashrc creates a couple of additional variables MYNAM and HOSTNAM (don’t use names for variables that can be confused with commands e.g. hostname) which extract my first name from the /etc/passwd file and the hostname up to the first dot in the fqdn returned by the hostname command.  These variables are then used to construct a friendly welcome message when you log in.

I’ve kept it simple, but you can be as elaborate as you like.

More reading here on colours etc (can be useful to colour the root user prompt red for example)…

http://www.cyberciti.biz/tips/howto-linux-unix-bash-shell-setup-prompt.html

CUSTOMISING THE TITLEBAR TO DISPLAY THE CURRENTLY EXECUTING COMMAND

To have the terminal window display the currently running command in the titlebar (useful info during long scrolling outputs), add the following to the .bashrc file in your home directory.

if [ “$SHELL” = ‘/bin/bash’ ]
then
    case $TERM in
         rxvt|*term)
            set -o functrace
            trap ‘echo -ne “\e]0;$BASH_COMMAND\007″‘ DEBUG
            export PS1=”\e]0;$TERM\007$PS1″
         ;;
    esac
fi



				
Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Matching an IP Address using sed

Regular expression for matching an IP address.

sed ‘s/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/&HelloWorld/gp’ infile > outfile

will append the string HelloWorld directly after an ipaddress in a file containing ipaddresses e.g.

10.200.200.10 blah

with

10.200.200.10HelloWorld blah

This can be adjusted to replace ip addresses with a string or used to inject some whitespace between an ipaddress and a string as required.

It looks more complicated than it is due to the many escape characters \ needed in the regular expression to tell the sed command that you’re passing a command and not a character to be matched.

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Copying the contents of one filesystem to another.

Sometimes on older operating systems, rsync (first choice for copying files from one filesystem to another) may not be available.  In such circumstances, you can use tar.  If it’s an initial copy of a large amount of data you’re doing, then this may actually be 2 – 4 times faster due to the lack of rsync’s checksum calculations, although rsync would be faster for subsequent delta copies.

timex tar -cf – /src_dir | ( cd /dest_dir ; tar -xpf – )

Add a v to the tar -xpf command if you want to see a scrolling list of files as the files are copied but be aware that this will slow it down.  I prefer to leave it out and just periodically ls -al /dest_dir in another terminal to check the files are being written correctly.  timex at the front of the command will show you how long it ran for once it completes (may be useful to know).

With the lack of verbose output, if you need confirmation that the command is still running, use ps -fu user_name | grep timex although the originating terminal should not have returned a command prompt unless you backgrounded the process with an & upon execution, or CTRL Z, jobs, bg job_id subsequently. Note that backgrounding the process may hinder your collection of timings so is not recommended if you are timing the operation.

Another alternative would be to pipe the contents of find . -depth into cpio -p thus using cpio’s passthru mode…

timex find . -depth | cpio -pamVd /destination_dir

Note that this command can appear to take a little while to start, before printing a single dot to the screen per file copied (the capital V verbose option as opposed to the lowercase v option)

If you wish to copy data from one block storage device to another, it’d be faster to do it at block level rather than file level.  To do this, ensure the filesystems are unmounted, then use the dd command dd if=/dev/src_device of=/dev/dest_device

Do not use dd on mounted filesystems.  You will corrupt the data.

Overall progress can be monitored throughout the long copy process with df -h in a separate command windowprepending the cpio command with timex will not yield any times once the command has completed – but it is faster than both tar or rsync for initial large copies of data.

To perform a subsequent catch-up copy of new or changed files, simultaneously deleting any files from the Destination that no longer exist on the Source for a true “syncronisation” of the two sides, much like a mirror synchronisation, use…

timex ./rsync -qazu –delete /src_dir/* /dest_dir  

Note this will not include hidden files.  To do that, lose the * off the source fs and add a trailing slash to the destination fs

or to catch up the new contents on the Src side to the Dest side and not delete any files on the Dest side that have been deleted on Src, use

rsync -azu –progress /NFS_Src/* /NFS_Dest

a= archive mode; equals –rlptgoD (recursive, links, permissions, times, group, owner and device files preserved)

z = compress file during transfer (optional but generally best practice)

u = update

–progress in place of v (verbose) or q (quiet).  A touch faster and more meaningful than a scrolling list of files going up the screen.

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash: