2

I have an alias alias ll='ls -lF';

I created a bash script temp.sh:

#!/bin/bash 

# Allow aliases to work in bash NON-interactive mode!
shopt -s expand_aliases

# .. and load them
source ~/.bash_aliases
$1

but when I run it it gives me:

$ ./temp.sh ll
./temp.sh: line 10: ll: command not found

and when I change the script and put the alias directly:

#!/bin/bash 

# Allow aliases to work in bash NON-interactive mode!
shopt -s expand_aliases

# .. and load them
source ~/.bash_aliases
ll

... it's working:

$ ./temp.sh   
total 12
-rwxrwxr-x 1 sobi3ch sobi3ch 423 Apr 19 14:21 script.sh*
-rwxrwxr-x 1 sobi3ch sobi3ch 196 Apr 26 12:28 temp.sh*
-rwxrwxr-x 1 sobi3ch sobi3ch 173 Apr 26 12:02 script2.sh

... also when I run the alias command in the script instead of ll (or $1) I can see the alias to ll between all aliases.

Why doesn't my alias work when I pass it as parameter?

2

This is not explicitly pointed out in the documentation (at least nowhere that I could notice), but the problem is that alias expansion takes precedence over variable expansion; that means that the $1 token is checked to see if it corresponds to an alias, discarded as a potential alias and only after that expanded as a parameter. Since there's no command named ll, Bash errors out.

You could use eval to make the parameter expand twice, the first time as a parameter and the second time as an alias:

#!/bin/bash 

# Allow aliases to work in bash NON-interactive mode!
shopt -s expand_aliases

# .. and load them
source ~/.bash_aliases
eval "$1"
~$ cat temp.sh 
#!/bin/bash 

# Allow aliases to work in bash NON-interactive mode!
shopt -s expand_aliases

# .. and load them
source .bash_aliases
eval "$1"  
~$ cat .bash_aliases 
alias ll='ls -l'
~$ ./temp.sh ll
drwxrwxr-x  3 user user 4096 apr 24 15:18 articles
drwxrwxr-x  2 user user 4096 apr 24 00:20 bin
drwxr-xr-x  2 user user 4096 apr 21 20:22 Documenti
-rw-r--r--  1 user user 8980 apr 21 20:18 examples.desktop
drwxr-xr-x  2 user user 4096 apr 21 21:59 Immagini
drwxr-xr-x  2 user user 4096 apr 21 20:22 Modelli
drwxrwxr-x  6 user user 4096 apr 23 20:45 MT7630E
drwxr-xr-x  2 user user 4096 apr 21 20:22 Musica
drwxr-xr-x  2 user user 4096 apr 21 20:22 Pubblici
drwxr-xr-x  2 user user 4096 apr 24 23:02 Scaricati
drwxr-xr-x  2 user user 4096 apr 24 13:44 Scrivania
-rwxrwxr-x  1 user user  149 apr 26 13:22 temp.sh
drwxrwxr-x  2 user user 4096 apr 26 13:22 tmp
drwxrwxr-x 24 user user 4096 apr 23 13:45 util-linux-2.28
drwxr-xr-x  2 user user 4096 apr 21 20:22 Video
| improve this answer | |
  • And that's the answer! :) – sobi3ch Apr 26 '16 at 11:36
  • @sobi3ch I suggest keeping a list with the order of the various shell expansions handy. Lots of time not wasted in fixing these things. ;) – kos Apr 26 '16 at 11:40

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.