9

I have created an alias in the .bashrc file:

alias java='java -Xmx1200m'

This alias works when I run a java command from my shell directly.

However, when the java command is inside a bash script (script.sh), this alias does not get activated. How do I ensure that the aliases in .bashrc file are accepted in a bash script ??

fedorqui
  • 275,237
  • 103
  • 548
  • 598
prathmesh.kallurkar
  • 5,468
  • 8
  • 39
  • 50

5 Answers5

7

Alias are not expanded in non-interactive shells.

The only way to make an alias is to source the target script with the one which contains the alias.

$ source .bashrc
$ . custom_script.sh
chepner
  • 497,756
  • 71
  • 530
  • 681
epsilon
  • 2,849
  • 16
  • 23
4

Quoting from the bash manual:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see The Shopt Builtin).

Saying the following in your script should make it work:

shopt -s expand_aliases
devnull
  • 118,548
  • 33
  • 236
  • 227
1

Aliases are limited to the shell and do not work in executed shell scripts. You are better off creating a variable.

jaypal singh
  • 74,723
  • 23
  • 102
  • 147
1

The simplest answer is to do the 2 important things or it wont' work. In your other script, do the following: -i for interactive mode, and shopt part as mentioned below.

#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

If you don't do that, you'll get an error:

your_cool_alias: command not found
AKS
  • 16,482
  • 43
  • 166
  • 258
0

You can run your script under bash bash in interactive mode; add -i to bash command line, like this script. Now you can use your aliases.

#!/bin/bash -i 

alias lsd='ls -al | grep ^d' 

lsd 
MichaelMoser
  • 3,172
  • 1
  • 26
  • 26