Arrays in Shell Scripts

I have defined an array like this:

   set -A MYARRAY

   MYARRAY[0]=file1
   MYARRAY[1]=file2
   MYARRAY[2]=file3
   MYARRAY[3]=file4

   i=0
   while [[ $i < ${#MYARRAY[@]} ]]
   do
     echo "File Name $i :"  ${MYARRAY[$i]}
     i=`expr $i + 1 `
     echo "value of i=" $i
   done

This works perfectly and shows the value of each element of array as file name.

Now my question is can I use the same while loop in SFTP command??

I looked at the FAQ but those for loops do not help. So my question is can this while loop somehow work??

Try this:

cat tarray.ksh
#!/bin/ksh

set -A A_VAL one two three four five six seven eight nine ten

i=0

while [ -n "${A_VAL[$i]}" ]
do
   echo "${A_VAL[$i]}"
   (( i = i + 1 ))
done

results:

./tarray.ksh  
one
two
three
four
five
six
seven
eight
nine
ten

---------- Post updated at 11:22 PM ---------- Previous update was at 11:07 PM ----------

I apologize. I didn't read your whole post... must be late...

Try this

#!/bin/ksh

set -A A_FILE file1 file2 file3 file4 file5 file6 file7 file8 file9 file10

i=0

while [ -n "${A_FILE[$i]}" ]
do
   sftp -o IdentityFile=${KEYFILE} ${FTPUSER}@${FTPSERVER} <<-EOF
      put ${A_FILE[$i]}
      quit
   #
   # The EOF must be TABbed over.  It can not be spaces.
   # 
   EOF
   (( i = i + 1 ))
done

This works in a while loop.

So my question is that if there are 10 files, it logs into the remote server 10 times.

So can the looping be made such that it connects to the server by SFTP ONCE and then loops 10 times??

I tried putting while loop after sftp command and it does not work.

   i=0
   sftp $USER_ID@$REMOTE_SERVER  <<-EOF      
   cd ${DIR}

     i=0
     while [[ $i < ${#MYARRAY[@]} ]]
     do
       echo "Value of i:"  ${i}
       echo "File Name $i :"  ${MYARRAY[$i]}
       put ${FILE_DIR}${MYARRAY[$i]}
       export i=`expr $i + 1 `
       echo "Value of i:"  ${i}
     done
     quit
   EOF

FOLLOWING WORKS FINE.

while [ -n "${A_FILE[$i]}" ]
do
   sftp -o IdentityFile=${KEYFILE} ${FTPUSER}@${FTPSERVER} <<-EOF
      put ${A_FILE[$i]}
      quit
   #
   # The EOF must be TABbed over.  It can not be spaces.
   # 
   EOF
   (( i = i + 1 ))
done

sftp supports the use of a batch file containing a list of commands you want to execute once connected.

#!/bin/ksh

#
# Define the batch file.
#
SFTP_BAT_FILE=files_to_send.bat

#
# Remove SFTP_BAT_FILE if if exists.
#
if [ -f "${SFTP_BAT_FILE}" ]; then
   rm -f ${SFTP_BAT_FILE}
fi

set -A A_FILE file1 file2 file3 file4 file5 file6 file7 file8 file9 file10

i=0

while [ -n "${A_FILE[$i]}" ]
do
   #
   # Append each file to the batch file.
   #
   echo "put ${A_FILE[$i]}" >> ${SFTP_BAT_FILE}

   (( i = i + 1 ))
done

echo "exit" >> ${SFTP_BAT_FILE}

sftp -b ${SFTP_BAT_FILE} -o IdentityFile=${KEYFILE} ${FTPUSER}@${FTPSERVER}
1 Like

This had worked perfectly. Thanks a lot again.