LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Test Within Here Document (https://www.linuxquestions.org/questions/linux-newbie-8/test-within-here-document-4175520612/)

Cleveland_Steve 09-30-2014 11:19 AM

Test Within Here Document
 
I've written the following Bash script, but it always returns files found even when the directory is empty. Can someone point out what I'm doing wrong?

Code:


#!/bin/bash

ssh node-prod-2 <<EOF
echo
hostname
echo
cd /opt/data/db1/Logs
pwd
if [ "$(ls -A)" ]; then
echo Files found.
else
echo Directory is empty.
fi
exit
EOF

exit 0


smallpond 09-30-2014 11:43 AM

To avoid aliases, change the command to $(/bin/ls -A)

Cleveland_Steve 09-30-2014 11:57 AM

Nope, same result. The script returns files found when the directory is empty.

szboardstretcher 09-30-2014 01:04 PM

This worked for me, empty and not-empty on Centos 6.
Code:

#!/bin/bash

ssh my-server <<EOF
echo
hostname
echo
pwd
[ "$(ls -A /tmp/not-empty)" ] && echo "Not Empty" || echo "Empty"
[ "$(ls -A /tmp/empty)" ] && echo "Not Empty" || echo "Empty"
exit
EOF

exit 0

Logic test output:
Code:

[root@dev]# mkdir /tmp/empty
[root@dev]# mkdir /tmp/not-empty
[root@dev]# touch /tmp/not-empty/FILE
[root@dev]# [ "$(ls -A /tmp/not-empty)" ] && echo "Not Empty" || echo "Empty"
Not Empty
[root@dev]# [ "$(ls -A /tmp/empty)" ] && echo "Not Empty" || echo "Empty"
Empty


Cleveland_Steve 09-30-2014 02:00 PM

That did not working either. The script is getting executed from node-prod-1. In both cases it looks like the (ls -A) command is executing in the directory on node-prod-1, when it should execute in the directory in node-prod-2 via the "ssh node-prod-2 <<EOF"

Cleveland_Steve 09-30-2014 04:17 PM

I just figured out my problem. For anyone who comes across this in the future, I needed single quotes around my EOF. Thanks to all who took a look.

Quote:

#!/bin/bash

ssh node-prod-2 << 'EOF'
echo
hostname
echo
cd /opt/data/db1/Logs
pwd
if [ "$(ls -A)" ]; then
echo Files found.
else
echo Directory is empty.
fi
exit
EOF

exit 0


All times are GMT -5. The time now is 01:58 AM.