1

I need to write a bash-script which will find all files with name string.h on the computer and copy them to some folder. My code is here:

#!/bin/bash
sudo find / -type f -name "string.h" -exec cp {} $HOME/MyDocuments

But during the execution of the script, I get error-messages on my console terminal "permission denied". Please, told me, how I can avoid getting this message? Console terminal must be clear.

3
  • 3
    Not an answer, but you lack \; at the end of the line, and if several files are called string.h they will all overwrite each other in the target directory.
    – Kusalananda
    May 15, 2017 at 8:52
  • 2
    Getting a "Permission denied" while root is somewhat interesting in itself. (NFS and SELinux or such come to mind)
    – ilkkachu
    May 15, 2017 at 9:50
  • Is $HOME/MyDocuments an existing directory, or are you expecting your script to create it?
    – resc
    May 15, 2017 at 9:54

1 Answer 1

0

The errors "permission denied" are "ok" if your find try to travel in directories where your user have no read-permission or the cp in your line try to write to a directory you have no access to. You can suppress them with redirecting stderr

#!/bin/bash
sudo find / -type f -name "string.h" -exec cp {} $HOME/MyDocuments \; 2>/dev/null

The pattern 2>/dev/null means to send all errors to "nowhere" instead of standard-error.

But sending error messages to /dev/null will not solve the error that your command will not have permission to read or to write.

3
  • 1
    One of the issues here is that the OP is running find with sudo. It is unclear what produces the errors.
    – Kusalananda
    May 15, 2017 at 11:26
  • That is right. Maybe there is an immutable-flag on one of the directories (maybe the $HOME/MyDocuments. Maybe we can check this with the output of lsattr -dfor the directory in question.
    – Michael
    May 15, 2017 at 11:35
  • Another issue here is that if there's more than a single matching file on your system, only the last one will be present in 'MyDocuments' after running that command.
    – Wildcard
    May 15, 2017 at 11:43

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.