Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running basename on remote server with xargs does not produce expected results

Say I have a file myFile.txt in a local directory called ~/local/directory, then the following command produces results as expected (full file path followed by the name of the file only):

find ~/local/directory -type f -iname '*myFile*' | xargs -I{} sh -c '{ echo {}; echo $(basename {}); }'

However, now let’s say I have a file myFile2.txt in a directory ~/test/directory on a remote system called remote-host. Trying to run the same command above remotely prints out the full file path both times as if basename were not working. What am I doing wrong?

ssh -q remote-host "find ~/test/directory -type f -iname '*myFile*' | xargs -I{} sh -c '{ echo {}; echo $(basename {}); }'"

(My ultimate goal is to run rsync on files returned by find in a remote environment and saving them back locally to a specific directory but a prefix added to the filename, thus the need for basename. This seems more doable using xargs instead of rsync’s -exec option.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to escape the $ so that it will be sent literally to the remote machine. Otherwise, $(basename {}) is executed locally, and the output {} is substituted into the ssh argument.

ssh -q remote-host "find ~/test/directory -type f -iname '*myFile*' | xargs -I{} sh -c '{ echo {}; echo \$(basename {}); }'"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading