0

Normally I have a .bashrc file where ll alias is set as

alias ll='ls -l'

When I invoke ll manually, it works just fine. However, sometimes I may need to run command from a string. So I would like to run:

COMMAND="ll"
bash --login -c "$COMMAND"

Unfortunately this complains that ll command is not found and fails. If I check alises it is indeed defined in this scope, I check like this:

COMMAND="alias"
bash --login -c "$COMMAND"

the above mentioned prints all my aliases properly.

Is there any way to use aliased commands in bash's -c command_string parameter?

0

A couple of things to note here, first about running with the --login option:

When bash is invoked as an interactive login shell, or as a non-inter‐
active shell with the --login option, it first reads and executes  com‐
mands  from  the file /etc/profile, if that file exists. After reading
that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile,
in  that order, and reads and executes commands from the first one that
exists and is readable.

So, this command is not reading your .bashrc. Secondly, aliases only work in interactive shells, so even if this alias were being sourced it would not work in your command. Functions, however, do work in non-interactive shells. So, you should convert your aliases to functions and source them in one of the things mentioned above, such as ~/.bash_profile.

Alternatively, you can export functions defined in the current environment to the one inherited by bash -c. I have this function:

adrian@adrian:~$ type fn
fn is a function
fn () 
{ 
    find . -name "$1"
}

Which I can call in a subshell like this:

adrian@adrian:~$ export -f fn
adrian@adrian:~$ bash -c "fn foo*"
./foo.bar
  • 1
    While it is correct that by default, are not expanded in non-interactive shells, this can be configured (using shopt expand_aliases). – user1934428 Nov 7 '17 at 9:39
0

.bashrc is only read under certain conditions, so make that happen:

$ cat ~/.bashrc
echo being read
alias foo='echo bar'
$ bash -c foo
bash: foo: command not found
$ bash -i -c foo
being read
bar
$ 

A quick skim through bash(1) for interactive then might turn up

   Aliases  are not expanded when the shell is not interactive, unless the
   expand_aliases shell option is set using shopt (see the description  of
   shopt under SHELL BUILTIN COMMANDS below).

which may give several other ways to enable this besides throwing -i into the argument list.

(That being said, I absolutely do not use aliases in non-interactive shells such as bash -c)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.