Bash Script with if, elif, else

2019-09-19 02:04发布

问题:

Okay so this is an assignment so I will not put in the exact script here but I am really desperate at this point because I cannot figure something as basic as if's. So I am basically checking if the two arguments that are written in the command line are appropriate (user needs to type it correctly) or it will echo a specific error message. However, when I put in a command with 100% correct arguments, I get the error echo message from the first conditional ALWAYS (even if I switch around the conditional statements). It seems that the script just runs the first echo and stops no matter what. Please help and I understand it might be hard since my code is more of a skeleton.

 if [ ... ]; then
 echo "blah"

 elif [ ... ]; then
 echo "blah2"

else for file; do
#change file to the 1st argument

done 
fi 

I obviously need the last else to happen in order for my script to actually serve its intended purpose. However, my if-fy problem is getting in the way. The if and elif need to return false in order for the script to run for appropriate arguments. The if and elif check to see if the person typed in the command line correctly.

回答1:

elif mean else-if. So it only will only be checked if the first statement returns false. So if you want to check if both are correct do.

if [ ... ] then
...
fi

if [ ... ] then
...
fi


回答2:

When you care about checking both the first and second command line arguments for a single condition (i.e. they must both meet a set of criteria for the condition to be true), then you will need a compound test construct like:

if [ "$1" = somestring -a "$2" = somethingelse ]; then
    do whatever
fi

which can also be written

if [ "$1" = somestring ] && [ "$2" = somethingelse ]; then
...

Note: the [ .... -a .... ] syntax is still supported, but it is recommended to use the [ .... ] && [ .... ] syntax for new development.

You can also vary the way they are tested (either true/false) by using -o for an OR condition or || in the second form. You can further vary your test using different test expressions (i.e. =, !=, -gt, etc..)