HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMinor

Three "alias-functions" in my .bashrc file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
threefilefunctionsaliasbashrc

Problem

These functions work well for me. Can they be improved or made more standard in some way?

Each function has a documentation header block, which contains a description of what it does, along with example usage and reference links where applicable.

:<<COMMENT
    Alias function for recursive deletion, with are-you-sure prompt.
    Example call:
        srf /home/myusername/django_files/rest_tutorial/rest_venv/

    Short description: Stored in SRF_DESC

    With the following setting, this is *not* added to the history:
        export HISTIGNORE="*rm -r*:srf *"
    - http://superuser.com/questions/232885/can-you-share-wisdom-on-using-histignore-in-bash

    See:
    - y/n prompt: http://stackoverflow.com/a/3232082/2736496
    - Alias w/param: http://stackoverflow.com/a/7131683/2736496
COMMENT
#SRF_DESC: For "aliaf" command (with an 'F'). Must end with a newline.
SRF_DESC="srf [path]: Recursive deletion, with y/n prompt\n"
srf()  {
    #Actual line-breaks required in order to expand the variable.
    #- http://stackoverflow.com/a/4296147/2736496
    read -r -p "About to
sudo rm -rf $1
Are you sure? [y/N] " response
    response=${response,,}    # tolower
    if [[ $response =~ ^(yes|y)$ ]]
    then
        echo -e "sudo rm -rf $1"
        sudo rm -rf "$1";
    else
        echo "Cancelled."
    fi
}


:<<COMMENT
    Delete item from history based on its line number. No prompt.

    Short description: Stored in HX_DESC

    Examples
        hx 112
        hx 3

    See:
    - http://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#HX_DESC: For "aliaf" command (with an 'F'). Must end with a newline.
HX_DESC="hx [linenum]: Delete history item at line number\n"
hx()  {
    history -d "$1";
}


```
: /tmp/history"
grep -v "$1" "$HISTFILE" > /tmp/history

#Clear all items in the current sessions history (in memory). This
#empties out $HISTFILE.
echo "history -c"
h

Solution


  • You never validate the contents/existence of $1



  • for instance: grep -v "" "$HISTFILE" returns nothing, so you're deleting your entire history.



  • You might want to use set -x, set +x instead of echo-ing the commands about to be done.

Context

StackExchange Code Review Q#77600, answer score: 6

Revisions (0)

No revisions yet.