1

I have this little bash script :

  #!/bin/bash

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

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.

3
  • 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

2

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:

  #!/bin/bash

  PATH1="/home/user100/files"
  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

./script.sh
3
  • 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.