PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to put if statement inside a lftp block

 October 30, 2022     bash, eof, if-statement, lftp, linux     No comments   

Issue

I am writing a bash script to download files from ftp server using lftp. I wanted to delete the files based on the second input argument.

#!/bin/bash

cd $1

lftp -u found,e48RgK7s sftp://ftp.xxx.org << EOF
set xfer:clobber on
mget *.xml
if [ $2 = "prod"]; then
  echo "Production mode. Deleting files"
  mrm *.xml
else
  echo "Non-prod mode. Keeping files"
fi
EOF

However, if statement is not allowed in the lftp block before EOF.

Unknown command `if'.
Unknown command `then'.
Usage: rm [-r] [-f] files...
Unknown command `else'.

How do I embed if statement in such block?


Solution

A command substitution will do:

#!/bin/bash

cd "$1" || exit
mode=$2

lftp -u found,e48RgK7s sftp://ftp.xxx.org << EOF
set xfer:clobber on
mget *.xml
$(
    if [ "$mode" = "prod" ]; then
      echo "Production mode. Deleting." >&2 # this is logging (because of >&2)
      echo "mrm *.xml"                      # this is substituted into the heredoc
    else
      echo "Non-prod mode. Keeping files" >&2
    fi
)
EOF

Note that inside the substitution for the heredoc, we're routing log messages to stderr, not stdout. This is essential, because everything on stdout becomes a command substituted into the heredoc sent to lftp.

Other caveats to command substitution also apply: They run in subshells, so a assignment made inside the command substitution will not apply outside of it, and there's a performance cost to starting them.


A more efficient approach is to store your conditional components in a variable, and expand it inside the heredoc:

case $mode in
  prod)
    echo "Production mode. Deleting files" >&2
    post_get_command='mget *.xml'
    ;;
  *)
    echo "Non-production mode. Keeping files" >&2
    post_get_command=
    ;;
esac

lftp ... <<EOF
set xfer:clobber on
mget *.xml
$post_get_command
EOF


Answered By - Charles Duffy
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing