0

Most of the time, an alias works well, but some times, the command is executed by other programs, and they find it in the PATH, in this situation an alias not works as well as a real file.

e.g.

I have the following alias:

alias ghc='stack exec -- ghc'

And I want to translate it into an executable file, so that the programs which depending on it will find it correctly. And the file will works just like the alias does, including how it process it's arguments.

So, is there any tool or scripts can help doing this?

luochen1990
  • 3,689
  • 1
  • 22
  • 37
  • Where is the program `ghc` located? It must be in your search `path` otherwise you must provide that information in the `alias`. – David C. Rankin May 21 '19 at 08:58
  • @DavidC.Rankin I have no ghc in my path, but the alias `stack exec -- ghc` works just like ghc, that's why I'm uing this alias, but other programs which trying to find ghc failed, So I want to mock a `ghc` in my path. – luochen1990 May 21 '19 at 09:48

2 Answers2

2

Here is my solution, I created a file named ghc as following:

#!/bin/sh
stack exec -- ghc "$@"

The reason why there is double quote around $@ is explained here: Propagate all arguments in a bash shell script

luochen1990
  • 3,689
  • 1
  • 22
  • 37
0

So, is there any tool or scripts can help doing this?

A lazy question for a simple problem... Here's a function:

alias2script() { 
    if type "$1" | grep -q '^'"$1"' is aliased to ' ; then 
        alias | 
        { sed -n "s@.* ${1}='\(.*\)'\$@#\!/bin/sh\n\1 \"\${\@}\"@p" \
                 > "$1".sh
          chmod +x "$1".sh
          echo "Alias '$1' hereby scriptified.  To run type: './$1.sh'" ;}
    fi; }

Let's try it on the common bash alias ll:

alias2script ll

Output:

Alias 'll' hereby scriptified.  To run type: './ll.sh'

What's inside ll.sh:

cat ll.sh 

Output:

#!/bin/sh
ls -alF "${@}"
agc
  • 7,973
  • 2
  • 29
  • 50