Search code examples
bashshellfish

How to perform parameter expansion in fish shell?


I have a bash program that uses parameter expansion to go back one level from the directory I'm on. For example, if I'm in the directory /path/to/my/dir, my program will allow me to go to /path/to/my/ without retyping the whole path or using cd - a bunch of times. Recently, I decided to start using the fish shell and I love it. But I'm not really sure how to do parameter expansion in the fish shell. I've tried to create an alias to my bash program in ~/.config/fish/config.fish so that back will run bash /path/to/back.sh, but this doesn't run the program in the current environment. Changing it to . /path/to/back.sh doesn't really help since fish doesn't know how to run a bash script.

I was wondering if there is a parameter expansion feature in fish? I tried reading the documentation and couldn't find it.

Any help would be appreciated.

Thanks.


Solution

  • Your back.sh script can't possibly work unless you are running it via . or source. That's because a child process cannot affect the environment, which includes the CWD, of any other process. If you run back.sh 1 it will only change the CWD of that script which isn't meaningful since the script immediately exits.

    Fish does support parameter expansion but not brace constructs like ${prev_dir%/*}. Fish prefers using commands for such manipulations rather than complex syntax. So, for example, to strip everything after the last slash you would do something like this in fish:

    set prev_dir (string split -r -m1 / $prev_dir)[1]
    

    And as one of the commenters noted you would normally just do cd .. to move up one level in the directory hierarchy. How often do you really need to move more than one level up? For me the answer is very rarely in which case I just do cd ../.. to move two levels.