Capture Multiple Lines Into Variable As Of Standard Output

Hello All,
I have the below script and output.

cat test.sh
#!/bin/bash -x
logit()
{
 echo "[${USER}][`date`] - ${*}" > ${LOG_FILE}
}
LOG_FILE=/home/infrmtca/bin/findtest.log

VAR=`find . -type f -name "*sql"`
logit $VAR

Output:

 cat /home/infrmtca/bin/findtest.log
[infrmtca][Fri May 31 15:02:59 EDT 2013] - ./dwh_StageDataValidation.sql ./dwh_MoveDataFromStageToWarehouse.sql

Here as you the output of find command is printed in same line in log file. Instead i would like it to be printed as a list as of standard output when you execute the find command like below. please help.

find . -type f -name "*sql"
./dwh_StageDataValidation.sql
./dwh_MoveDataFromStageToWarehouse.sql

Expected Output:

[infrmtca][Fri May 31 15:02:59 EDT 2013] - 
dwh_StageDataValidation.sql
dwh_MoveDataFromStageToWarehouse.sql

Using GNU find:

echo -e "[${USER}][$(date)] -\n$(find . -type f -name "*sql" -printf "\t%f\n")"

I find it amusing that you use the -printf option of find, yet feel the need to use echo -e to use \n, rather than use printf!

I modified my script as per your inputs but still not getting desired output.

#!/bin/bash -x
logit()
{
 echo "[${USER}][`date`] -\n${*}" > ${LOG_FILE}
}
LOG_FILE=/home/infrmtca/bin/findtest.log

VAR=`find . -type f -name "*sql" -printf "\t%f\n"`
logit $VAR

Output:

[infrmtca][Fri May 31 15:36:40 EDT 2013] -\ndwh_StageDataValidation.sql dwh_MoveDataFromStageToWarehouse.sql

You need to double quote $VAR when you call logit, otherwise the newlines are lost to word splitting.

Regards,
Alister

@Scott, I thought of using printf instead of echo .

But using format specifiers with printf would make the code appear cryptic, hence used echo instead.

The echo in logit needs an -e option in order to interpret the \n correctly.

I know, but standard echo doesn't have a -e option! And printf doesn't require format specifiers.

-- Anyhoo, sorry, I didn't mean to hijack the thread :slight_smile:

You only need to quote!

logit "$VAR"

Always quote variables in command arguments!

@Scott,

I know that format specifiers are not mandatory for printf

But I have seen Alister mentioned about Uncontrolled Format String which is a vulnerability and is a security risk.

So I used echo for simplicity. Thanks.