0

I want to write a command opening a a Jupyter Notebook in firefox but I am struggling with bash.

# This is what I want to achieve:
$ firefox --new-tab localhost:8888/tree/notebooks/my_notebook.ipynb

So far I can echo the url to the notebook:

$ cd notebooks
$ var="my_notebook.ipynb"
$ echo localhost:8888/tree/${PWD}/${var} | sed 's/\/home\/johndoe\///g'
localhost:8888/tree/Dropbox/notebooks/my_notebook.ipynb

How to pass the string above to a firefox command? I tried to use command substitution $(), piping |, quotes, but without success.

I am assuming that jupyter-notebook is running from my home directory /home/johndoe. Bonus points if you can pass $HOME to that sed command

SOLUTION: I created a function (not an alias) that opens Jupyter Notebook in firefox on a file or a directory as follows:

nb() { 
firefox --new-tab "$(echo localhost:8888/tree/$(realpath --relative-to="$HOME" "${PWD}")/$1)" & 
}

aless80
  • 3,122
  • 3
  • 34
  • 53

1 Answers1

2

I tried to use command substitution $(), piping |, quotes, but without success.

Really? It's just:

firefox --new-tab "$(echo localhost:8888/tree/${PWD}/${var} | sed 's/\/home\/johndoe\///g')"

Bonus points if you can pass $HOME to that sed command

Use a different separator - with ~ you should be safe enough. And learn about quoting in shell.

sed "s~$HOME~~g"

You can get relative path with:

realpath --relative-to="$HOME" "$PWD"

Any idea how to place it in an alias using $1 instead of $var?

Use a function

some_function() {
    if (($# == 0)); then
        echo "Missing argument"
        return 1
    fi
    firefox --new-tab "localhost:8888/tree/$(realpath --relative-to="$HOME")/$1"
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Any idea how to place it in an alias using $1 instead of $var? I still cannot get the $1 right – aless80 Mar 03 '21 at 16:34
  • @aless80 Aliases don't take arguments; use a function instead. – Gordon Davisson Mar 03 '21 at 17:10
  • @GordonDavisson ok I'll try that, though you can read posts of people using $1 in aliases in some shells. – aless80 Mar 03 '21 at 21:07
  • @aless80 You can do that in csh (and derivatives like tcsh), but not in any Bourne-family/POSIX shell (bash, zsh, ksh, dash, etc). See [this question](https://stackoverflow.com/questions/7131670/make-a-bash-alias-that-takes-a-parameter). Warning: if you define a function and *also* have an alias by the same name, the alias will take precedence (and probably not work); be sure to `unalias` first. – Gordon Davisson Mar 03 '21 at 21:44