Home > front end >  Bash run sh command stored in variable
Bash run sh command stored in variable

Time:12-16

I'm trying to make a script like this one: (main script taking two args)

#!/bin/bash

set -e

function runSh(){
  sh "$1"
}

if [ $(whoami) != "root" ]; then
   sesu root
fi

PATH="$1"

cd $PATH
for folders in */; do
   cd $folders
   for files in *; do
       if [[ $files == deploy_es* ]]; then
           runSh $files $2       ***it fail here with 'sh command not found', $files here is a sh script like `deploy_es_test.sh`***
       fi
   done
   cd ..
done

my question is, how can i run sh script stored in the variable $files ?

  1. I tried to run it through runSh function,
  2. with eval $files $2
  3. with $(sh $files $2)

none works, i suppose i'm not using the good method to run it, thx for your help !

CodePudding user response:

The reason it doesn't find sh is that you set PATH that is a special variable that defines the places where bash will look for binaries/scripts.

By setting PATH="$1" bash will not be able to find anything.

BTW: you don't really need to do that loop:

CMD="cat"
[ $(whoami) != "root" ] && CMD="sudo cat"
find $1 -maxdepth 1 -name deploy_es\* -exec $CMD {} \;

is probably enough.

As to the question you placed, bash doesn't require you to eval the command in general as you can see here:

$ ls -l /tmp/a
totale 4
-rw------- 1 root   sandro 5 dic 15 15:13 deploy_es.txt
$ CMD=cat
$ find /tmp/a -name deploy_es\* -exec $CMD {} \;
cat: /tmp/a/deploy_es.txt: Permesso negato
$ CMD="sudo cat"
$ find /tmp/a -name deploy_es\* -exec $CMD {} \;
ciao
  •  Tags:  
  • bash
  • Related