orschiro
orschiro

Reputation: 21715

Bash: Output all aliases and functions in a script

Take the following script:

shopt -s expand_aliases
set -f
result=$(compgen -A function)
echo $result

When running it outputs all my custom bash functions:

mp3gain pkg-pkgbuild-download quote quote_readline restart standby turnoff turnoff-timer youtubeConvert

However, when slightly changing the script to output aliases, the output is empty:

shopt -s expand_aliases
set -f
result=$(compgen -A alias)
echo $result

Yet it is not empty if I run compgen -A alias directly.

My aliases are stored in ~/.bash_aliases and my functions in /.bash_functions. Both are sources in ~/.bashrc:

# Functions
if [ -f ~/.bash_functions ]; then
        . ~/.bash_functions
fi

# Aliases
if [ -f ~/.bash_aliases ]; then
        . ~/.bash_aliases
fi

What am I missing here?

Upvotes: 1

Views: 210

Answers (1)

bos
bos

Reputation: 6535

I'd be willing to wager that the aliases are not sourced. This can be verified running this simple script:

#!/bin/bash
alias

If there is no output, the aliases are not sourced. Hence, that's why compgen returns an empty list when put in a script (non-sourced aliases) but works fine when run manually in a shell with sourced aliases.

Solution: put "source ~/.bash_aliases" near the top of your script to make sure they are invoked before running.

Upvotes: 1

Related Questions