Hacker News new | ask | show | jobs
by photon-torpedo 589 days ago
Good question. Something to do with interactive mode?

  $ cat l.sh
  alias l=ls
  l
  $ sh l.sh
  file1  file2  l.sh
  $ bash l.sh
  l.sh: line 2: l: command not found
  $ bash -i l.sh
  file1  file2  l.sh
Edit: Ah yes, the man page says so.

> Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt

2 comments

Thanks, I had no idea. I guess I've never used aliases in scripts, but I would've assumed that they'd just work the same as in interactive mode. Good to know.
Why use an alias in a script? Or in general? Functions work everywhere.
Functions don't work everywhere. Bash functions only work in the current shell context unless exported via an `export -f myfun' statement in between the function declaration and downstream sub-shell usage.

Working example:

  pzoppin() {
      printf 'echo is for torrent scene n00bs from %s\n' "$*"
      trap "printf '%s\n' <<< \"$*\"" RETURN EXIT SIGINT SIGTERM
  }
  export -f pzoppin

  echo -e 'irc\0mamas donuts\0starseeds' \
      | xargs -0 -n 1 -I {} /usr/bin/env bash -c '
  echo hi
  pzoppin "$*"
  echo byee
  ' _ {}
The above will fail miserably without the magic incantation:

  `export -f pzoppin'
Why'd they design an otherwise perfectly usable, mapless language without default c-style global functions? :)
I suppose aliases predated functions. Can't find a reference to support that, though. Just a possible reason.

BTW aliases come from csh, and there they support arguments, which makes them similar to functions.

Aliases are like C macros

    $ alias foo='seq 3 | '
    $ foo cat
    1
    2
    3
Functions are functions
So then use $variables for evil syntactic tricks? That works everywhere. Functions where hygiene counts? Aliases never?
>use $variables for evil syntactic tricks

Can't do that without eval, which is another can of worms. Aliases are fine

Indeed, here are two lines atop my "util.sh" to regularize some strange non-conformant behaviours:

  [ "${BASH:-}" ] && shopt -s expand_aliases
  [ "${ZSH_VERSION:-}" ] && setopt SH_WORD_SPLIT