h0ch5tr4355
h0ch5tr4355

Reputation: 2192

How can I write a bashrc alias, that can call itself?

I have following setup:

In my ~/.bashrc I only call a script, where my actual settings are stored in:

source C:/path/To/mybashrc.sh

As you might see I use the git-bash for Windows (not sure, if that is important):

$ bash --version
GNU bash, version 4.4.23(1)-release (x86_64-pc-msys)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Now I want to create a command, that makes me able to edit this script directly. I found out how to get the directory of the script (1) and in another post I found out how to get the scripts name itself (2).

# Edit this file with nano
#(1)
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
#(2)
script_name=`basename "$0"`
# script_name="mybashrc.sh" # This works.
alias mybashrc='nano ${__dir}/${script_name}'

However my problem is that I can't combine these two solutions. When I try the script it opens a file called bash in the right directory in nano and not mybashrc.sh. The problem is probably the sourcing of the script in .bashrc and I wonder if I can still get to the desired solution. I am looking forward towards any hints. (Of course the out-commented line works as the name is hard-coded, but that is not a solution for me as the script names differ in the real-world scenario, that I have.)

Upvotes: 1

Views: 190

Answers (1)

KamilCuk
KamilCuk

Reputation: 141920

The path is already in ${BASH_SOURCE[0]}. Your code takes directory from ${BASH_SOURCE[0]} and filename from $0. So don't take it from $0, take it from BASH_SOURCE[0].

alias mybashrc="nano ${BASH_SOURCE[0]}"

However, BASH_SOURCE[0] may be relative. So let's make sure it's absolute.

alias mybashrc="nano $(readlink -f "${BASH_SOURCE[0]}")"

will break on paths with spaces. A more experienced shell programmer may write:

alias mybashrc="nano $(printf "%q" "$(readlink -f "${BASH_SOURCE[0]}")")"

Or you could use a variable that expands upon use, but still remember to quote the expansion:

thescript=$(readlink -f "${BASH_SOURCE[0]}")
alias mybashrc='nano "$thescript"'

Upvotes: 2

Related Questions