I have this little bash script :


  CMD1=$(find . -type f -iname "*.sh" -exec rm -fr {} +;)
  cd $PATH1

If I run one by one the commands they are all executed successfully, if I run the script it just does nothing at all.

Any help or idea would be appreciated.

  • What are the contents of the CMD1 variable? Replace $CMD1 in the last line with echo "$CMD1". Probably you are doing something very wrong...
    – FedKad
    Jun 15, 2020 at 8:52
  • 2
    You now deleted all .sh files from below your current location. Hopefully it was not / or ~.
    – pLumo
    Jun 15, 2020 at 9:00
  • 2
    It runs the find in ., your cwd, and removes any .sh files in there. (Being as find recurses, and you picked files and not directories, the -r in remove is junk.) Anyway, that find returns nothing - it does the commands, but there is no data from stdout. So CMD1 is empty. Then you cd to another directory, and run an empty command. What exactly did you intend it to do? Jun 15, 2020 at 9:01

1 Answer 1


if you want to store a command as string in a variable you shouldn't use $()

 CMD1="find . -type f -iname '*.sh' -exec rm -fr {} +;"

Then you call the variable later using eval command.. So your script should be something like:


  CMD1="find . -type f -iname '*.sh' -exec rm -fr {} +;"
  cd $PATH1
  eval $CMD1;

Then don't forget to give execute permission for the script

chmod +x script.sh

Then run the script

  • exec will never run with arguments if you don't use eval
    – Maythux
    Jun 15, 2020 at 9:43
  • You're absolutely right! it chokes on the internal quoting without the eval as well.
    – terdon
    Jun 15, 2020 at 10:10
  • Without eval, find ... exec throws an error because of the (unneeded) semicolon in +;, which is not seen as a control operator when resulting from an expansion and thus prevents find from recognizing the +. Assuming we have reasons for executing a command as a result of parameter expansion (which are not evident here), the risks from eval can be avoided by using an array, e.g. cmd=( find ... '*.sh' ... {} + ); "${cmd[@]}" as Kusalananda pointed out in comments to a now-deleted answer. (Sorry for reposting, my previous comment included a major mistake).
    – fra-san
    Jun 15, 2020 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.