0

I have only one condition to check. And i would like to use the if-else construct in shell script. How do i write it. Most of the docs show that the construct is doing multiple aspects thats why they use

if []; then
 echo "do something"
elif
 echo "somethingelse"
else
 echo "something 2"
fi

But in my case i am writing my construct like the below. It gives syntax issues.

#!/bin/sh
hadoopFileList=`hadoop fs -ls /app/SmartAnalytics/Apps/service_request_transformed.db/sr_denorm_bug_details/ | sed '1d;s/  */ /g' | cut -d\  -f8`
destination="/apps/phodisvc/creandoStaging"

scpData()
{
 for file in $hadoopFileList
 do
  echo $file
  echo "copying file to the staging directory"
  hadoop fs -copyToLocal $file $destination
  sleep 2s
  echo "deleting the file"
  echo ${file##*/}
 done
}

if [[ -d "$destination" ]]; then
#file exists copy data
 scpData()
else
#else create directory and copy data
 mkdir -p $destination
 scpData()
fi
4
  • mkdir -p already does nothing (successfully) when the directory exists. Why do you have the if at all? Commented Sep 21, 2017 at 5:57
  • @DavisHerring comments were written for stackoverflow users sake. Commented Sep 21, 2017 at 5:58
  • 1
    One Reason: You should not call your function with () wrong: scpData() right: scpData only function definition needs () Commented Sep 21, 2017 at 6:00
  • @PS. wow thanks. I have been coding in java and other languages. I was not able to understand why the script was failing. Thanks for noticing that. Commented Sep 21, 2017 at 6:02

2 Answers 2

1

You should not call your function with (), only definition needes them.

wrong:

myFunction() {
echo "This line is from my Function"
}

myFunction()

Right way:

myFunction() {
echo "This line is from my Function"
}

myFunction
Sign up to request clarification or add additional context in comments.

Comments

0

As PS. mentioned, a bash function like scpData should be called without (). Other than that, your if[];then ... else ... fi syntax is correct. Thus your if-loop will work as:

if [ -d "$destination" ]; then
    scpData
else
    mkdir -p $destination
    scpData
fi   

In this particular case, however, the if-loop is not necessary, because mkdir's -p option does check the condition. i.e., it only makes directory if it doesn't exist. So I re-wrote your if-loop (without using if-else-fi) as following:

mkdir -p $destination
scpData

which does the same thing!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.