1

I am writing a shell script to do some complex task which is repetitive in nature. To simplify the problem statement, the last step in my complex task is to copy a file from a particular path (which is found based on some complex step) to a pre-defined destination path. And the file that gets copied will have the permission as 600. I want this to be changed to 644.

I am looking at an option where in I can instruct the system to copy that file and change the permission all in one command. Something like - cp -<some_flag> 644 <source_path> <destination_path>

You may say, I can change the permission of the file once it is copied in a 2 step process. However, there is problem with that as well. Reason being, the source path is obtained as an output of another command. So I get the absolute path for the file and not just the file name to write my script to call chmod with a name.

My command last segment looks like - ...| xargs -I {} cp {} /my/destination/path/

So I dont know the name of the file to call chmod after the copy

Darshan L
  • 279

1 Answers1

3

Just include the chmod in your xargs call:

...|  xargs sh -c 'for file; do 
                      cp -- "$file" /my/destination/path/ && 
                        chmod 700 /my/destination/path/"$file"; 
                    done' sh

See https://unix.stackexchange.com/a/156010/22222 for more on the specific format used.

Note that if your input to xargs is a full path and not a file name in the local directory, you will need to use ${file##*/} to get the file name only:

...|  xargs sh -c 'for file; do 
                  cp -- "$file" /my/destination/path/ && 
                    chmod 700 /my/destination/path/"${file##*/}"; 
                done' sh
terdon
  • 242,166
  • @steeldriver ah yes, good point. Depends on what the OP is doing of course, and we have no information to go on. – terdon Nov 03 '20 at 14:50
  • Yeah, it worked with the modification what @steeldriver mentioned. Thanks both. – Darshan L Nov 03 '20 at 14:56
  • Glad to hear it! Since we now know it's needed, I added steeldriver's improvement to the answer. – terdon Nov 03 '20 at 14:58