Search code examples
bashshellfish

How to pass argument to alias/function in bash and fish at once


My question is very similar to: How to pass command line arguments to a shell alias?

I want to create alias that will accept arguments. Guys in above question suggested functions and indeed this is solution.

However, I am using at once fish (Friendly Interactive SHell) and bash. I keep all my custom aliases in single file, that I load no matter if I am using fish or bash.

I know how to create alias/functions in bash, and I know how to create alias/functions in fish. I do not know, how to create alias/function at once for both fish and bash.

It doesn't have to be alias/function (it can be edgy hack), just end effect should work like expected.

alias rmi="function _rmi() { docker ps -a | grep $1 | awk '{print $1}' | xargs --no-run-if-empty docker rm -f ; docker images | grep $1 | awk '{print $3}' | xargs --no-run-if-empty docker rmi -f }; _rmi()"

Above one is accepted by bash, but not fish.

function go sudo service $argv restart end

Above is accepted by fish, but now bash.

alias apts="aptitude search"

Plain aliases as above one are accepted by both bash and fish, but argument cannot be inside (must be at very end).

How to unify it?


Solution

  • There is no proper general solution to this, fish is not compatible with bash.

    Also, the alias something="function" is unnecessary. You can just define the function directly.

    If what you wish to execute does not change anything about the shell's internal state, you can make a script instead.

    E.g. create a file called "rmi" that contains

    #!/bin/bash
    docker ps -a | grep $1 | awk '{print $1}' | xargs --no-run-if-empty docker rm -f
    docker images | grep $1 | awk '{print $3}' | xargs --no-run-if-empty docker rmi -f
    

    somewhere in $PATH (in both bash and fish).