Home > database >  Very Short Form of Bash Script Not Working :)
Very Short Form of Bash Script Not Working :)

Time:06-15

The script is basically polling directory /images for jpg files and moving them to new directory /gallery/2022-06-14/ while also renaming (removing initial characters). I was planning to add another action along where if existing time is between 000000 and 050000, bash script should invoke python script by taking renamed file path as argument.

Can you tell if its not possible to use short form of if in this manner? Why its erroring out?

find '/images' -maxdepth 1 -name '*jpg' -exec sh -c '''echo mv {} /gallery/$(date --date="today" ' %F')/$(basename {} | sed "s/^.\{,19\}//") && [[ ! ( `date  "%H%M%S"` < 000000 || `date  "%H%M%S"` > 050000 ) ]] && python3 python-script.py "/gallery/$(date --date="today" ' %F')/$(basename {} | sed "s/^.\{,19\}//")"''' \;
sh: 1: Syntax error: "(" unexpected
sh: 1: Syntax error: "(" unexpected
sh: 1: Syntax error: "(" unexpected
sh: 1: Syntax error: "(" unexpected
sh: 1: Syntax error: "(" unexpected
sh: 1: Syntax error: "(" unexpected
sh: 1: Syntax error: "(" unexpected
sh: 1: Syntax error: "(" unexpected
sh: 1: Syntax error: "(" unexpected

CodePudding user response:

if its not possible to use short form of if in this manner?

It is possible.

Why its erroring out?

That specific error is most probably because you used sh instead of bash. [[ is super special for Bash with special syntax rules and it specially handles (.

Anyway, the code is unreadable, and uses an find extension and is not protected against spaces in filenames and has issues. Do not use backticks, prefer $(...). Consider a different approach, where you do not have to super double quote everything:

work() {
  echo "$somevar"
  somevar2="$2"
  # normal code here, you could use variables.
  echo mv "$1" "/gallery/$(date --date="today" ' %F')/$(basename "$1" | sed "s/^.\{,19\}//")"
  if [[ ! ( $(date  "%H%M%S") < 000000 || $(date  "%H%M%S") > 050000 ) ]]; then
     python3 python-script.py "/gallery/$(date --date="today" ' %F')/$(basename "$1" | sed "s/^.\{,19\}//")"
  fi
}
somevar=1
export somevar
export -f work
somevar2=2
find .... -exec bash -c 'work "$@"' _ {} "$somevar2" \;
  • Related