I have a very wierd case… If I run a script with /bin/bash, it can't recognize aliases that I set even inside the script. And the most strange thing is
$ cat -n test.sh
1 #!/bin/bash
2 alias somecommand='ls -alF'
3 alias
4 somecommand
$ ./test.sh
alias somecommand='ls -alF'
./test.sh: line 4: somecommand: command not found
… as shown above, if I run the command "alias" in the script it turns out that bash has taken somecommand into the aliases, but if I run the somecommand itself it will still not be recognized!
Everything is right if I use the command "sh" to run the script.. so is it a bug of bash? Or is there something I'm missing?
Any help is appreciated!
Best Answer
Simply don't use aliases in scripts. It makes little sense to use a feature designed for interactive use in scripts. Instead, use functions:
Functions are much more flexible than aliases. The following would overload the usual
ls
with a version that always doesls -F
(arguments are passed in$@
, including any flags that you use), pretty much as the aliasalias ls="ls -F"
would do:The
command
here prevents the shell from going into an infinite recursion, which it would otherwise do since the function is also calledls
.An alias would never be able to do something like this:
This creates the function
select_edit
which takes directory as an argument and asks the user to pick a file in that directory. The picked file will be opened in an editor for editing.The
bash
manual contains the statement