i wish to write a fish shell script to automatically initialize JAVA_HOME to current configured java-alternative.
In bash it would look like this (sorry for the ugly double dirname)
j=`update-alternatives --query javac | grep Value:`
JAVA_HOME=`dirname ${j#Value:}`
JAVA_HOME=`dirname $JAVA_HOME`
export JAVA_HOME
what about fish?
set j (update-alternatives --query javac | grep Value:)
set JAVA_HOME (dirname ${j#Value:}) <-- this won't work!!
set JAVA_HOME (dirname $JAVA_HOME)
set --export JAVA_HOME
The fish shell now has a string
builtin command for string manipulation. This was added in version 2.3.0 (May 2016).
E.g. in this case, we could use string replace
to remove the Value:
substring:
set j (update-alternatives --query javac | grep Value: | string replace 'Value: ' '')
set --export JAVA_HOME (dirname (dirname $j))
There's lots more that string
can do. From the string command documentation:
Synopsis
string length [(-q | --quiet)] [STRING...]
string sub [(-s | --start) START] [(-l | --length) LENGTH] [(-q | --quiet)]
[STRING...]
string split [(-m | --max) MAX] [(-r | --right)] [(-q | --quiet)] SEP
[STRING...]
string join [(-q | --quiet)] SEP [STRING...]
string trim [(-l | --left)] [(-r | --right)] [(-c | --chars CHARS)]
[(-q | --quiet)] [STRING...]
string escape [(-n | --no-quoted)] [STRING...]
string match [(-a | --all)] [(-i | --ignore-case)] [(-r | --regex)]
[(-n | --index)] [(-q | --quiet)] [(-v | --invert)] PATTERN [STRING...]
string replace [(-a | --all)] [(-i | --ignore-case)] [(-r | --regex)]
[(-q | --quiet)] PATTERN REPLACEMENT [STRING...]