5

How can I do bash style string manipulations in Fish shell?

Specifically, in bash

read branch < ".git/HEAD"
branch=${branch#ref: refs/heads/}

will put the branch name in $branch variable.

How can I do the same in fish shell?

I glanced over documentation of fish but didn't find anything.

  • I already got this working with sed. I was wondering if fish has something builtin. – blackwing Mar 5 '14 at 4:45
6

The fish shell now has a string builtin command.

To use string instead of sed in your case:

set branch (string replace 'ref: refs/heads/' '' <.git/HEAD)

It can operate on given arguments, or on standard input.

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...]
3

fish is all about minimalism: if there's a common utility that does the job easily, it's not in fish. So, as you say, with sed:

set branch (sed 's#^ref: refs/heads/##' .git/HEAD)

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.