Bash Notes
Categories:

Advanced command history substitution

Execute previous command with a string replacement (only works on first string)

$ ls *.tmp

$ ^ls^rm
rm *.tmp

$ cp -i file1 file2 file3 destdir

$ ^-i    # no 2nd string replaces with nothing
cp file1 file2 file3 destdir

Replace all occurrences of string in previous command:

$ echo 4 4 4 4 4

$ !:gs/4/5/
echo 5 5 5 5 5

Access previous commands:

$ls -l *.txt

$ !!    # run the last command
ls -l *.txt

$ !-1    # same as !!
$ !-2    # run the command before the last one
$ !-3    # run the 3rd previous command

Access the parameters of the previous command:

$ cp file1 file2 file3 destdir

$ echo !$
destdir

$ echo !*
file1 file2 file3 destdir

Scripting

Parse command-line options:

for i in $*
do
    case $i in
    -v|--verbose)
        VERBOSE=1
        ;;
    -h=*|--host=*)
        HOST=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
        ;;
    *)
        echo "Invalid option" >&2
        ;;
    esac
done