I'm trying to write a Bash shell script that copies all the files in the current directory, minus a few exceptions, into another directory. The script builds a command, stores it in a variable, and runs it. Here's the baffling part: when the command it builds is run in a shell script, it fails with the message find: paths must precede expression: `|xargs'
If I remove the space before the |
, I instead see find: unknown predicate `-i'
. But when I echo
the command it builds and run it, it works fine! To make it even weirder, echo "$cmd"|bash
fails with the same error message!
The script (synchronize.sh
):
#! /bin/bash
EXCLUDED_FILES=(folder1 file.txt synchronize.sh)
FLAGS='-r'
PROJECT_NAME=project
TARGET_DIR=$HOME/Documents/IDE/$PROJECT_NAME/assets
cmd='find ./* -maxdepth 0'
cmd_end="|xargs -i cp -r {} -t $TARGET_DIR"
for file in ${EXCLUDED_FILES[@]}
do
cmd+=" ! -name \"$file\""
done
cmd+=$cmd_end
$cmd #Running the command directly fails
#echo $cmd #Yet copying and pasting the output of this command will work just fine
#echo "$cmd"|bash #Though this inexplicably fails, with the same message as just $cmd
None of the files or folders have spaces in their name, or any special characters except underscores and periods.
find … | xargs …
line without thiscmd
contraption. But if you want it then: How can we run a command stored in a variable? (2) "None of the files or folders have spaces in their name, or any special characters except underscores and periods." – Don't let it be your excuse. It's a virtue to do things in the right way anyway. Why does my shell script choke on whitespace or other special characters?find
command is...not ideal. I ended up rewriting your script using an array comparison just because I was curious how the workflow looked. Since it's off-topic to the subject of this question I'm just adding a gist. gist.github.com/iamwpj/12cb157d82578a2383b28ec1fa259c3e