Bash Scripting – Troubles Piping Echo Output to xargs Script for mv Command

bashcommand linescriptsxargs

and thank you in advance for any advice.

I'm working on a script that will automatically sort my downloads. The script is very simple, and running it manually has the intended effect. The problem I'm having is with the fswatch command that's intended to trigger the script – I can't get the output from echo correctly piped into xargs. Here's the command:

fswatch --event Created Downloads/ | (while read x; do echo $x | xargs -0 bash ./dlsort.sh; done)

and the script:

if (echo "$1" | grep -q '\.jpg$'); then
  mv "$1" Desktop/images/ &
else
  mv "$1" Downloads/other/ &
fi

I've determined what the issue is, I just don't know how to correct it. a newline character is getting put at the end of the filename, which causes the mv command to fail with a "no such file or directory" error in the script. I've been experimenting with quite a few variations in both the echo and fswatch commands, but nothing I've tried has worked.

Thanks again to anyone who can help with this

Best Answer

Figured out a good answer to this specific problem:

Use the fswatch option --format="%p%0". This makes sure that the null character is at the end of the path name that gets handed off to xargs, which is what it's looking for with the -0 option enabled.

Related Question