Script run with shebang does not resolve aliases, how to circumvent?
Non-interactive bash
won't expand aliases even if your script defines them (defines directly or by sourcing another file, explicitly or not); unless shopt -s expand_aliases
.
I don't know zsh
but I think this is irrelevant. Aliases are fine in your daily command line routine but in general they are not meant to be used in scripts. You should solve the problem without them in a shell-agnostic way.
I don't know WSL either. The following methods are quite basic in Linux, they should work.
A symlink:
ln -s "/full/path/to/docker.exe" "/some/dir/in/your/PATH/docker"
This way you will be able to run
docker.exe
under the namedocker
in (or even without) any shell. One disadvantage: ifdocker.exe
is moved to another location then the symlink will stop working. You will need to remove it and recreate with the new path todocker.exe
.A wrapper script:
#!/bin/sh # adjust the shebang if needed exec docker.exe "$@"
Save it as
docker
in some directory inPATH
; make the file executable. Now if you rundocker
, the script willexec
todocker.exe
. Again, callingdocker
will work in any shell, if only yourPATH
variable leads todocker
anddocker.exe
.
Aliases are often used to "inject" an option (or options). Although this is not your case, let's make the answer more general. Consider alias ll='ls -l'
. You cannot create a symlink that does this. You can however make a script, the relevant line would be:
exec ls -l "$@"
Your .bashrc
or whatever file your setup uses should have a line like this: [[ $- != *i* ]] && return
which will abort sourcing the resource file if it isn't an interactive shell. Thus your aliases are not sourced, because they are for interactive convenience.
To use an alias in you shell script you need to source a file of aliases or define the alias in the script.
Ultimately, it will be more lines of code to do this, and you are better off just calling the .exe
file directly in the script.
NB. We really shouldn't source an alias file or our .bashrc
into a script, because they are likely to change.
I hope this helps. Please let me know if you have any other questions.