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.