1

I've been writing a lot of one-off functions recently. On the occasions that I go "hmm, I should save this" I use type <function name> to show the code, and copy and paste it into .bashrc. Is there a faster way to do this, or some standard or command built for this purpose?

FWIW, I'm just doing this on my personal computer running Mint, so conveniences like copy and paste are easy. However, I'm also interested in answers specific to shell-only environments.

3

In Korn-like shells, including ksh, zsh, bash and yash, you can do:

typeset -fp myfunc

To print the definition of the myfunc function.

So you can add it to the end of your ~/.bashrc with:

typeset -fp myfunc >> ~/.bashrc
| improve this answer | |
  • So there is a suitable command! Thank you. – user67459 Oct 18 at 1:11
3

some standard or command built for this purpose

I don't know, but you can use type + tail + redirection

For example, I have a function edit(). Here is my type edit output:

edit — это функция
edit () 
{ 
    for arg in "$@";
    do
        if which "$arg" > /dev/null; then
            subl $(realpath $(which "$arg"));
        else
            echo "$arg not found";
        fi;
    done
}

To supress first line edit — это функция I use tail -n +2:

$ type edit | tail -n +2
edit () 
{ 
    for arg in "$@";
    do
        if which "$arg" > /dev/null; then
            subl $(realpath $(which "$arg"));
        else
            echo "$arg not found";
        fi;
    done
}

Then I need to redirect this output to .bash_profile or .bashrc or whatever else: type edit | tail -n +2 >> $HOME/.bash_profile

Now let's check if edit is really a function: type -t edit will output only one word function if its argument is a function.

Final solution looks like:

add_to_bash_profile() {
    local type_of_arg="$(type -t $1)"
    if [ "$type_of_arg" == "function" ]
    then 
        echo >> $HOME/.bash_profile #adding empty line for readability of .bash_profile
        type $1 | tail -n +2 >> $HOME/.bash_profile
    else
        echo "$1 is not a function"
    fi
}

and now you can add this function to your .bash_profile:

add_to_bash_profile add_to_bash_profile
| improve this answer | |
  • 1
    You can also check that .bash_profile contains such function by grepping it. – user432155 Oct 17 at 9:10
  • 1
    Very nice answer! I would put type function | tail -n+2 >> ~/.bashrc in a TL;DR (note that OP uses .bashrc, not .bash_profile). – Quasímodo Oct 17 at 11:16
  • 1
    I really appreciate the answer and the time you took walking through each step! +1 for teaching me "it's a function" in Russian. – user67459 Oct 18 at 1:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.