1

I like using bash aliases quite often (I am using .zshrc) but I would prefer that the aliases would show what they do. This is because I have to pair program quite often. I know doing type alias_name and also alias alias_name displays a description. Is there a way to get my aliases to display their full form before they run? I tried prepending my aliases like alias alias_name='type alias_name && ...'. However the output for this would also include the prepended code as expected. Is there a way around it?

  • I can only think of some hack where you stick special comments in your alias file, something like `# alias_name: command blah`, and the alias itself would look like `alias_name='sed -n "s/^# alias_name: //p" ~/.zshrc; command blah`'. – Benjamin W. Sep 26 '21 at 19:04
  • Thank you @BenjaminW. , it is a bit hacky but seems to be doing the job fine so thank you – Hammad Muhammad Mehmood Sep 26 '21 at 19:23
  • Or without the comments, but with a more complicated sed command, something like `alias sodemo='sed -n "s/alias sodemo.*\.zshrc; \(.*\)./\1/p" ~/.zshrc; echo blah'` – Benjamin W. Sep 26 '21 at 19:34
  • `zshrc` in `bash`? Are you sure that you use `bash` and not `zsh`? – Socowi Sep 26 '21 at 20:22
  • how about `set -x` ? – jhnc Sep 26 '21 at 20:55

1 Answers1

3

In bash and zsh you can define a command that prints and executes its arguments. Then use that command in each of your aliases.

printandexecute() {
  { printf Executing; printf ' %q' "$@"; echo; } >&2
  "$@"
}
# instead of `alias name="somecommand arg1 arg2"` use 
alias myalias="printandexecute somecommand arg1 arg2"

You can even automatically insert the printandexecute into each alias definition by overriding the alias builtin itself:

printandexecute() {
  { printf Executing; printf ' %q' "$@"; echo; } >&2
  "$@"
}
alias() {
  for arg; do
    [[ "$arg" == *=* ]] &&
    arg="${arg%%=*}=printandexecute ${arg#*=}"
    builtin alias "$arg"
  done
}

# This definition automatically inserts printandexecute
alias myalias="somecommand arg1 arg2"

Example in an an interactive session. $ is the prompt.

$ myalias "string with spaces"
Executing somecommand arg1 arg2 string\ with\ spaces
actual output of somecommand
Socowi
  • 25,550
  • 3
  • 32
  • 54