Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Friday, 27 September 2013

bash history tricks

I came across an interesting blog entry about maintaining a persistent history of commands across multiple bash sessions using some features of bash I was unaware of.

First there was a variable PROMPT_COMMAND which will run the command stored in the variable before presenting the new prompt.

Then there was the BASH_REMATCH variables, which store substring patterns when used with [[ ... ]] e.g.

test_string="Random string of numbers : 1234"
[[
   $test_string =~ (.*)\:\ +([0-9]+)
]]

echo ${BASH_REMATCH[0]}
echo ${BASH_REMATCH[1]}
echo ${BASH_REMATCH[2]}

This snippet will output the following
Random string of numbers : 1234
Random string of numbers
1234

I have simplified the example from Eli's blog as I am not using the same format for history output , so my code in .bashrc looks like

log_bash_history()
{
  [[
    $(history 1) =~ ^\ *[0-9]+\ +(.*)$
  ]]
  local command="${BASH_REMATCH[1]}"
  if [ "$command" != "$HISTORY_LAST" ]
  then
    echo "$command" >> ~/.persistent_history
    export HISTORY_LAST="$command"
  fi
}

export PROMPT_COMMAND=log_bash_history

Friday, 21 June 2013

Refreshing memory on some basics

While going back across some Linux basics (always worth doing periodically), I was reminded of the command xfs_freeze. This command can also work on other journalled filesystems such as ext3, ext4, btrfs etc.

Also messing around with getopts bash builtin and getopt command, sample test script using getopts below

#!/bin/bash

if [ $# -eq 0 ] # Script invoked with no command-line args
then
echo "Usage: `basename $0` [-a] [-b] [-c] [-d <arg>]"
exit 99

fi

#first : suppresses error reporting from getopts
while getopts ":abcd:" option
do
case $option in
a ) echo "option a OPTIND=${OPTIND}";;
b | c ) echo "option $Option OPTIND=${OPTIND}";;
d ) echo "option d with argument \"$OPTARG\" OPTIND=${OPTIND}";;
* ) echo "Default error with options given";; # Default.
esac
done

exit $?


Note to self there must be a better way of displaying sample code in this blog.