LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   my if elif else statement in bash is not giving me the desired result (https://www.linuxquestions.org/questions/linux-newbie-8/my-if-elif-else-statement-in-bash-is-not-giving-me-the-desired-result-4175666184/)

dan-german 12-18-2019 11:19 AM

my if elif else statement in bash is not giving me the desired result
 
my question is:

1) i wrote an if,elif,else statement which ran successfully and gave me the desired output,but when i placed that same statement in a bash function,it did not run successfully. i can not figure out where am getting wrong.please can someone help me go through my bash script,thank you.

1) This if,elif,else statement ran succesfully


#!/bin/bash

Variable1="$1"
Variable2="$2"

if [ "$#" -eq 0 ]
then
echo "provide an argument"

elif [ "$#" -ne 1 ] && [ "$#" -ne 2 ]
then
echo "Surplus argument provided"
else

echo "have got your back"
fi



2) When i put the above statement in a bash function,it did not give me the desired results.

#!/bin/bash

Variable1="$1"
Variable2="$2"

AddVariable () {

Variable1="$1"
Variable2="$2"

if [ "$#" -eq 0 ]
then
echo "provide an argument"

elif [ "$#" -ne 1 ] && [ "$#" -ne 2 ]
then
echo "Surplus argument provided"
else

printname "$Variable1"
deletename "$Variable2"

fi

}

deletename(){

for file in $Variable2/*;do

echo "$(rm -i "$file")"
echo "deleting $Variable"

done
}
printname(){
Variable=$1
for file in $Variable1/*;do

echo "$(basename "$file")"
done
}

#printname "$Variable1"
#deletename "$Variable2"
AddVariable

please i am new to bash scripting thank you

MensaWater 12-18-2019 12:12 PM

Positional parameters ($1, $2, $3, etcc...) are relative to what they're being passed into.

On invocation of your script you're using $1 and $2 as passed into the script at invocation which is correct.
Code:

Variable1="$1"
Variable2="$2"

However, your function is also expecting two variables passed into it as shown:

Code:

AddVariable () {

Variable1="$1"
Variable2="$2"

When you later run AddVariable to call that function at end of script you are not passing any variables into it so $1 and $2 aren't populated. You should make your final line:
Code:

AddVariable $Variable1 $Variable2
Within the function you might consider changing Variable1="$1" to a different name (e.g. FVariable1="$1") to avoid confusing the variable name within the function with the similar one outside the function.

rtmistler 12-18-2019 07:57 PM

Please post your thread in only one forum. Posting a single thread in the most relevant forum will make it easier for members to help you and will keep the discussion in one place. This thread is being closed because it is a duplicate.


All times are GMT -5. The time now is 04:27 AM.