Search code examples
bashzsh

function to modify bash command based on condition


The current state of the function is like:

function git() {
    if  [[ $@ =~ ^"d untrack-all" ]]
    then
        echo "g d rm --cached -r ~"
    elif [[ $@ =~ ^"d add-and-commit" ]]
    then
        echo "g d add ~ && g d commit -am \"$_\""
    elif [[ $@ =~ ^"d sb" ]]
    then
        echo "git d branch | rofi -dmenu | xargs git checkout"
    elif [[ $@ =~ ^"d stash-and-reset" ]]
    then
        echo "git d stash && git d reset --hard HEAD"
    elif [[ $@ =~ ^"d last" ]]
    then
        echo "git d --no-pager log -1 --oneline"
    else
        echo $0" "$@
    fi
}

What I am expecting is,

if I run the command git d untrack-all it will actually run g d rm --cached -r ~ if I run the command git d add-and-commit it will actually run g d add ~ && g d commit -am \"$_\" ... If the pattern does not match, it will run the command as it is. For example, if I run git status, it will run git status.

In the given codem If I replace echo with eval, it closes the terminal. What should I do?


Solution

  • You don't need to use echo so:

    echo "g d rm --cached -r ~" 
    

    should be:

    g d rm --cached -r ~
    

    etc. In the last case, you can run

    bash -c $0" "$@