Is there a way to build a command in a script and then execute it within the script with an alias?

41 views Asked by At

I am creating a command in a variable then trying to assign the variable to an alias. If I do this at the command line, it works just fine, but when I put it in a script, it tells me command not found.

Here is the code I have in my script for building the command, setting the alias and then executing it:

fn_find_inode() {
    filename=$1
    cmd=""
    end_of_file=0
    while [[ $end_of_file == 0 ]]; do
        read -r line
        # the last exit status is the
        # flag of the end of file
        end_of_file=$?
        if [ $end_of_file != 1 ]; then
            #echo $line
            inodenum=$(ls -i $line | awk '{print $1}')
            #echo $inodenum
            cmd=$cmd" | grep -v $inodenum"
        fi
    done < $filename
                }
                
cmd1='list_readu EVERY DETAIL | grep " RU "'
fn_find_inode "/u2/eclipse/modules/ECL/scripts/other_scripts/exlrulocksfiles.txt"

cmd1=$cmd1$cmd' | sort -k2 -k7'
echo $cmd1
cd /u2/eclipse || exit 1
alias rulocks=$cmd1
alias rulocks > /tmp/rulocks.txt
source /tmp/rulocks
rulocks

This results in an error, command not found. If you source the file at the command line and the run rulocks you get no such error. I have tried to directly execute cmd1, but that results in an incorrect listing as the grep's are ignored and only the list_readu is executed. Any ideas on how to make this work?

1

There are 1 answers

3
SIMULATAN On

That's because aliases defined in scripts aren't persisted outside of it.

When you run this script:

alias helloworld="echo hello world"

in a shell, you can observe that helloworld can't be found. However, when you source the file, it suddenly exists.