Not able to store command inside a shell variable, and run the variable

Hi,

I am trying to do the following thing

var='date'
 
$var

Above command substitutes date for and in turn runs the date command and i am getting the todays date value.

I am trying to do the same thing as following, but facing some problems,

unique_host_pro="sed -e ' /#/d' \$configFile | awk -v appcode=\"$appcode\" -F\"\$config_del\" '{ if (\$1 == appcode ) print \$0 }' | awk -v unique_host=\"\$unique_host\" -F\"\$config_del\" '{ if ( \$2 == unique_host ) print \$0 }'"

I have stored the sed command in unique_host_pro variable and going to use the variable in multiple places of my script, so i dont have to use the command in multiple places, and also trying to avoid updates to the command in multiple places.

once assigning the above value, i am trying to run the command using

$unique_host_pro
 

Getting the following exception

checkProcess.sh: line 97: sed -e ' /#/d' $configFile | awk -v appcode="$appcode" -F"$config_del" '{ if ($1 == appcode ) print $0 }' | awk -v unique_host="$unique_host" -F"$config_del" '{ if ( $2 == unique_host ) print $0 }': No such file or directory

Please let me know how to correct this error also let me know if the approach is correct.

In order to reuse an existing code you should use a shell function.
You get the above error because the shell tries to execute the saved pipeline as a single command.

Thanks, So do you mean that pipline command should not be stored and reused ?

My code is like following

function checkProcessIdeHosts()
{
 unique_host=$1
 
 no_unique_hosts_prc=`sed -e ' /#/d' $configFile | awk -v appcode="$appcode" -F"$config_del" '{ if ($1 == appcode ) print $0 }' | awk -v unique_host="$unique_host" -F"$config_del" '{ if ( $2 == unique_host ) print $0 }'|wc -l`
 if [ $no_unique_hosts_prc -eq 1 ]
 then 
  checkProcessModule `sed -e ' /#/d' $configFile | awk -v appcode="$appcode" -F"$config_del" '{ if ($1 == appcode ) print $0 }'| awk -v unique_host="$unique_host" -F"$config_del" '{ if ( $2 == unique_host ) print $0 }'`
 else
  for proc_det in `sed -e ' /#/d' $configFile | awk -v appcode="$appcode" -F"$config_del" '{ if ($1 == appcode ) print $0 }'| awk -v unique_host="$unique_host" -F"$config_del" '{ if ( $2 == unique_host ) print $0 }'`
  do
          checkProcessModule $proc_det 
   sleep 5
  done
 fi
}

I am using the command "sed -e ' /#/d' $configFile | awk -v appcode="$appcode" -F"$config_del" '{ if ($1 == appcode ) print $0 }' | awk -v unique_host="$unique_host" -F"$config_del" '{ if ( $2 == unique_host ) print $0 }'" in multiple places, in case of updates to the command then I have to make the same changes in multiple places, i want to get rid of that, i can not use functions for this kind of substitutions

No, I'm just saying that you need to encapsulate the repeating code in another function :slight_smile: