Alias not working

I have several shell scripts which contain the nawk command.

Here is what i m doing assign the correct value to nawk as nawk is not found on a new systems.

Here is what i did.

more test.sh

[[ -x /usr/bin/gawk ]] && alias nawk=/usr/bin/gawk
[[ -x /usr/bin/nawk ]] && alias nawk=/usr/bin/nawk
[[ -x /usr/bin/awk ]] && alias nawk=/usr/bin/awk
nawk

Failed Output:

bash -x ./test.sh
+ source dr.profile
++ [[ -x /usr/bin/gawk ]]
++ alias awk=/usr/bin/gawk
++ [[ -x /usr/bin/nawk ]]
++ [[ -x /usr/bin/awk ]]
++ alias nawk=/usr/bin/awk
++ nawk
dr.profile: line 4: nawk: command not found

./test.sh: line 4: nawk: command not found

I was expecting nawk to become /usr/bin/awk
Can you suggest what is wrong ?

Aliases usually do not work in noninteractive scripts, just terminal sessions.

Try sourcing it, rather than running it directly, . test.sh That will run it directly in your shell.

Sourcing works when in terminal but like i said i need nawk to be recognised automatically in all my scripts.

I tried these but both failed.

more test1.sh

. test.sh
nawk

Output:

./test1.sh
test.sh: line 4: nawk: command not found
./test1.sh: line 2: nawk: command not found

I also tried source test.sh instead of . test.sh but it also did not work.

What am i missing here ?

Aliases usually do not work in noninteractive scripts, just terminal sessions. You could turn it on, but then you'd want to be really really careful what other aliases you might have loaded from /etc/profile without realizing it.

For situations like this, I usually see a variable used, like $NAWK .

This also prevents the sort of recursions you've fought when using functions for this.

Are you suggesting this would work ?

[[ -x /usr/bin/gawk ]] && NAWK=/usr/bin/gawk 
[[ -x /usr/bin/nawk ]] && NAWK=/usr/bin/nawk 
[[ -x /usr/bin/awk ]] && NAWK=/usr/bin/awk
$NAWK

Yes, exactly.

2 Likes

Alias works also in in noninteractive scripts.

Make own rc-file if not like add this to default rc-file:

$HOME/.xxrc file:

alias nawk='echo No nawk'
for awk in /usr/bin/gawk /usr/local/bin/gawk /usr/bin/nawk /usr/bin/awk
do
        [ -x "$awk" ] && alias nawk="$awk" && break
done
# test echo - you will see this test msg everytime when you start shell
echo "Myawk:$awk" >&2

Example add line to the $HOME/.bashrc:

[ -f $HOME/.xxrc ] && . $HOME/.xxrc

If you are ksh user then add same line to the $HOME/.kshrc or setup ENV

ENV=$HOME/.xxrc
export ENV

After those rc setup, always when you execute bash or ksh, shell will source .xxrc.
I'm sure that bash has also same method as ksh has ENV variable method to setup rc-file, but I didn't check it.

ls -al | nawk '{print $1}'

Wrong for many shells, including his. It won't run aliases by default without enabling them in shopt. (See Aliases )

Besides which, rc files aren't used when running a noninteractive script. Please read the topic more carefully.