Home > front end >  linux command find and its placeholder {} in multiline commands
linux command find and its placeholder {} in multiline commands

Time:01-02

I struggle with bash and the command find and its placeholder {} when using -execdir and the multiline escaping with """ for easy reading.

I want to iterate the folder $SOURCE and create an tar archiv of each folder at the folder $TARGET if this tar doesn't exist.

I tried many variants of escaping {} but I was not able to save the current folder in a variable. I would like to know how this placeholder works and how I could save its value to a variable in a multiline command.

One liner is working

find "$SOURCE" -mindepth 1 -maxdepth 1 -type d -execdir sh -c 'DIR="{}";echo $DIR' \;

returns

./2007_10_03 Event1
./2007_10_12 Event2

But not as a multiline command with sh and -c

find "$SOURCE" -mindepth 1 -maxdepth 1 -type d \
  -execdir sh -c """

DIR="{}"
echo $DIR

""" \;

return

sh: line 2: Event1: command not found
sh: line 2: Event2: command not found

CodePudding user response:

Like this:

find "$SOURCE" -mindepth 1 -maxdepth 1 -type d -exec sh -c '
    dir="$1"
    echo "$dir"
' sh {} \;    

This is most readable and safer than using {}

CodePudding user response:

Three double quotes is python's syntax to make multiple-line strings.

But in bash, """ is equivalent to a single quote: '.

You can use single quotes as in your first command :

find "$SOURCE" -mindepth 1 -maxdepth 1 -type d -execdir sh -c '
    DIR="{}"
    echo "$DIR"
' \;
  • Related