-1

My operating system is Ubuntu Linux 18.04 (Xubuntu) and bash version 4.4.19

By entering the following shell commands:

  • bash -c 'foo="echo bar" && $foo'
  • bash -c 'alias foo="echo bar" && foo'
  • alias foo="echo bar" && foo

I get the following output:

  • bar (expected)
  • bash: foo: command not found (a simple bar was expected)
  • bar (expected)

The reason I ask is because I have a complicated script, which uses aliases, that I would like to execute as root.

I have tried:

  • sudo bash -c '/path/to/script.sh'

But the script fails when using its own aliases. Unfortunately, switching to root (sudo -i) isn't an option in my desired case scenario.

LogicalException
  • 566
  • 2
  • 7
  • 16
  • 4
    Scripts shouldn't use aliases -- they're explicitly in the POSIX sh standard as an optional interactive extension, not a core shell-language feature. Use functions instead. – Charles Duffy Jan 04 '19 at 16:22
  • 1
    If `alias foo="echo bar" && foo` produces `bar`, you have a pre-defined alias named `foo`; alias expansion in that line occurs *before* the `alias` command ever runs. – chepner Jan 04 '19 at 16:24
  • Huh. I need to correct myself a bit: As of Issue 7 (POSIX.1-2017), aliases have moved from the User Portability extensions into the POSIX sh baseline spec. Nonetheless, they're very much a newcomer to the spec, whereas functions have been in the core specification since initial publication (in 1992). – Charles Duffy Jan 04 '19 at 16:28
  • lol chepner, you're right. – LogicalException Jan 04 '19 at 17:06
  • Hopefully aliases will mature. – LogicalException Jan 04 '19 at 17:10
  • @Charlie, ...I'm not sure they're ever going to mature *into a replacement for functions* -- the whole thing that gives aliases any kind of separate utility is their status as a syntax-unaware prefix substitution facility. Makes them inappropriate for 99% of use cases, but in the other 1%, a function is unusable but an alias works; if they "matured" into something effectively equivalent to a function, then would would the point of having them at all be? – Charles Duffy Jan 04 '19 at 17:33
  • ...as an example of one of those rare corner cases where an alias does something a function can't, consider `alias DEBUG=":; #"` in https://github.com/niieani/bash-oo-framework/blob/master/lib/oo-bootstrap.sh (aside: I don't recommend that project, or that code style, to anyone; linked here only as an example). With that alias, `DEBUG "$(...)"` doesn't run at all, not even run-and-discard-its-result -- you can't do that with a function, since a function (like every other command) has its arguments evaluated before invocation. – Charles Duffy Jan 04 '19 at 17:37

1 Answers1

0

Aliases are enabled by default only in interactive shells. When you start a shell with bash -c '...', it is not interactive.

Use functions instead: bash -c 'foo() { echo bar; } && foo' works perfectly.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441