Liondancer
Liondancer

Reputation: 16469

iterating through ls output is not occurring in bash

I am trying to ls the directories and print them out but nothing is being displayed. I am able to SSH and execute the first pwd. However, anything within the the for loop has no output. I know for sure there are directories called event-test- because I've done so manually. I've manually entered the directory (/data/kafka/tmp/kafka-logs/) and ran this piece of code and the correct output appeared so I'm not sure why

manually entered has correct output:

for i in `ls | grep "event-test"`; do echo $i; done;

script:

for h in ${hosts[*]}; do
        ssh -i trinity-prod-keypair.pem bc2-user@$h << EOF
                sudo bash
                cd /data/kafka/tmp/kafka-logs/

                pwd
                for i in `ls | grep "event-test-"`; do
                        pwd
                        echo $i;
                done;
                exit;
                exit;

EOF

done

Upvotes: 0

Views: 479

Answers (2)

Reverend
Reverend

Reputation: 11

When parsing ls it is good practice to do ls -1 to get a prettier list to parse. Additionally, when trying to find files named "event-test-" I would recommend the find command. Since I am not completely sure what you are attempting to do other than list the locations of these "event-test" files I'd recommend something more similar to the following:

for h in "${hosts[@]}"; do ssh trinity-prod-keypair.pem bc2-user@$h -t -t "find /data/kafka/tmp/kafka-logs/ -type f -name *event-test-*;" ; done

This will give you a pretty output of the full path to the file and the file name.

I hope this helps.

Upvotes: 1

anubhava
anubhava

Reputation: 784948

It is because

`ls | grep "event-test-"`

is executing on your localhost not on remote host. Besides parsing ls is error prone and not even needed. You can do:

for h in "${hosts[@]}"; do
   ssh -t -t trinity-prod-keypair.pem bc2-user@$h <<'EOF'
   sudo bash
   cd /data/kafka/tmp/kafka-logs/
   pwd
   for i in *event-test-*; do
       pwd
       echo "$i"
   done
  exit
  exit
EOF
done

Upvotes: 3

Related Questions