expand alias in shell script

Defining an alias within a shell script

If there’s a need to define an alias within a shell script, shopt needs to be defined to tell the script to expand the alias. This option is enabled by default for interactive shells, but not for non-interactive shells hence the need to use the shopt builtin.

For more information, read the manpage on shopt.

Here is a working example:

#!/bin/bash  
shopt -s expand_aliases

rel=`cat /etc/virtuozzo-release | awk '{ print $3 }'`

if [ "$rel" = "4.6.0" ]; then
  FS=1
else
  FS=0
fi

if [ "$1" = "debug" ]; then
        alias echo='echo -ne'
        cnt=1
        vzlist -aHh 0*.netsolvps.com -o veid > veids.txt
        #/bin/cat -n ./veids.txt
else
        cnt=''
fi

for veid in `vzlist -aHh 0*.netsolvps.com -o veid`
do

  echo "$cnt "
  if [ $FS -eq 1 ]; then
        KEYPATH="/vz/private/$veid/fs"
        /bin/grep key-number $KEYPATH/root/etc/sw/keys/keys/*
  else
        KEYPATH="/vz/private/$veid"
        if [ -d $KEYPATH/root/etc/sw/keys/keys ]; then
            /bin/grep key-number $KEYPATH/root/etc/sw/keys/keys/*
        else
            /bin/grep PLSK $KEYPATH/root/etc/psa/psa.key
        fi
  fi

  if [ ! -z "$cnt" ]; then
        cnt=`expr $cnt + 1`
  fi

done

One way around this is to use the eval command instead, whereby a user can assign a command to a variable and execute the variable as a command. In this example, the variable debug is assigned the value of “echo -n”, which is the command to suppress newline character from the default behavior of the echo command. This way, I won’t have to check any flags should I want to DEBUG the output of the results.

the option DEBUG would have to be passed to the script name as the first argument in the command line to suppress the newline character as it outputs the value of veid. Otherwise, if DEBUG is omitted, then a “silent” echo is output to the screen which goes unnoticed since the newline character has been surpressed.

#!/bin/bash  
debug="echo -n"
if [ "$1" == DEBUG ]; then
  debug="echo -n \${veid}','"
fi

for veid in $(vzlist -1h 0*.netsolvps.com)
do
  #echo CTID depending on whether or not DEBUG was passed as option to command
  **<span style="color: rgb(255, 0, 0);">eval $debug</span>**

  if [ -d /vz/private/$veid/fs ]; then
        KEYPATH="/vz/private/$veid/fs"
        key=`/bin/egrep -i "key-number|:domains " $KEYPATH/root/etc/sw/keys/keys/*`
  else
        KEYPATH="/vz/private/$veid"
        if [ -d $KEYPATH/root/etc/sw/keys/keys ]; then
            key=`/bin/egrep -i "key-number|:domains " $KEYPATH/root/etc/sw/keys/keys/*`
        else
            key=`/bin/egrep -i "Key number: |Number of Domains:" $KEYPATH/root/etc/psa/psa.key`
        fi
  fi

  echo $key | grep -i key
done
Share