LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Is aliases available in shell scripts? (https://www.linuxquestions.org/questions/programming-9/is-aliases-available-in-shell-scripts-4175458439/)

ravisingh1 04-17-2013 04:40 AM

Is aliases available in shell scripts?
 
I define aliases and save in rc file. what I see is that it isn't available in shell scripts. They are however available in interpretive or interactive sub-shell which I get when I give command
Code:

bash
For ex.:
Code:

I define
alias echo='echo -n'

it's unavailable in shell scripts but sub-shells.

druuna 04-17-2013 04:46 AM

Storing your aliases in an rc file (which one?) is not the way to go.

If you want to make them global I would suggest putting them in /etc/profile (or /etc/profile.d/). If you need them locally store them in ~/.profile (or ~/.bash_aliases).

millgates 04-17-2013 04:54 AM

Also, expansion of aliases is usually disabled in non-interactive shells (scripts).
You can put
Code:

shopt -s expand_aliases
in your script to enable them.

konsolebox 04-17-2013 05:56 AM

It's better to use functions than aliases.

And if you're wrapping a builtin, you could use builtin to call the builtin.
Code:

function echo {
    builtin echo -n "$@"
}

^ Although replacing echo with such default functionality is not recommended.

ravisingh1 04-17-2013 09:31 AM

konsolebox, please elaborate. What you mean by builtin

konsolebox 04-17-2013 10:01 AM

Oh yeah I didn't check. It's a feature in bash, and I'm referring to bash builtins. Run 'help builtin' if you're in bash. And run 'help' without any argument to see the list of those.

See the Bash manual for more info.

David the H. 04-18-2013 03:14 PM

Aliases are not enabled by default in shell scripts. As mentioned, they can be enabled with shopt, but even then that only makes it possible to create them in the script. You won't get immediate access to all the aliases in the main shell. Since aliases can't be exported, there's no way for a sub-process like a script to inherit a copy of them.

Aliases are rather pointless to use inside scripts anyway. Since you only need to write each command once, there's no real need for such user-interactive style shortcuts. It would also tend to make the code less obvious.

As mentioned, if you need to define code that will be used multiple times, or want to simplify longer commands, use functions.

BTW, if you just want to shorten up a longer command that has regularly-defined option strings, you can store them in an array first.

Code:

options=( -x -n -a foobar --long-option=bazbum )
mycommand "${options[@]}" filename.txt

As for "echo -n", I'd recommend using printf instead, whenever you need anything fancier than the default echo.


All times are GMT -5. The time now is 04:09 AM.