Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop in shell script not working on remote server

Tags:

linux

shell

ssh

The code tries to ssh from my local server to remote server and runs some commands.

ssh root@$remoteip 'bash -s' <<END3               
gcdadirs=`strings binary | egrep '.gcda$'`       
for dir in ${gcdadirs[@]}; do
directory=$(dirname ${dir})
echo $dir >> dirstr.txt
mkdir -p $directory
chown $root:$root $directory
chmod 777 $directory
done
END3

the above creates a directory structure on remote server which is working fine.

I want to tar up the same directory structure. so i'm using same logic as above.

ssh root@$remoteip 'bash -s' <<END3   
touch emptyfile
tar -cf gcda.tar emptyfile
gcdadirs=`strings binary | egrep '.gcda$'`
for dir in ${gcdadirs[@]}; do
tar -rf gcda.tar $dir
done
END3

The above piece of code should create a tar with all the directories included returned by for loop. i tried the code logic by copying the code to remote server and running it there and it worked. But if I ssh connect from my local server to remote server and try it is not enetring the for loop. it is not appending anything to tar file created with empty file in second line.

like image 950
Shashank Avatar asked Feb 13 '26 06:02

Shashank


1 Answers

Try <<'END3'

Note the quotes around END3, they prevent shell substitutions inside the here-document. You want the $-signs to be transferred to the other side of the ssh connection, not interpreted locally. Same for the backticks.


Extracted from the comments as the accepted answer. Posting as community wiki

like image 183
Henk Langeveld Avatar answered Feb 15 '26 21:02

Henk Langeveld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!