0

I'm learning how to use bash to write my first script for college, but I'm having trouble with nested statements/loops/functions.

I'm trying to write an if statement where if a variable value is true, it breaks/returns out of that if statement, then also breaks out of a containing while loop, that is also part of a function, that I want to end (when the if statement's variable is true).

I've tried return N, break N, and exit (I now know this just ends the script.) Here is an example of how I have attempted to set my script up.

#!/bin/bash

function1()
{
    while read -p "Enter a value: " input
    do
        if [ $input="X" ]
        then
            return 2
        fi
        # Rest of while statement
    done
    # End of while loop.
}
# End of function.

function1
# Call function1.
# Rest of script

Can anyone shed any knowledge on how this should work please? (I do apologise for the appalling formatting of this question, I'm new to the site and haven't really sat down and spent time to learn how it works, sorry.)

  • Never mind, after taking a break from researching how to figure this out and writing this question, I went back to my script with fresh eyes and immediately spotted the issue. if [ $input="X" ] Should be: if [[ $input="X" ]] I just thought I'd add this comment in case it helps anyone in future. – Jamjar91 Dec 9 '16 at 0:17
  • That's not true... you can use [] for some operations like you are using to compare with a string... but you must put spaces before and after the equal symbol. I answered putting your script corrected. – OscarAkaElvis Dec 9 '16 at 0:18
0

This is what you want:

#!/bin/bash

function1() {

    while read -p "Enter a value: " input; do

        if [ $input = "X" ]; then
            return 2
        fi

    # Rest of while statement
    done
    # End of while loop.
}
# End of function.

function1 # Call function1. # Rest of script

As simple as put spaces before and after "=" and using simple [] for the conditional.

-1
if [ $input="X" ]

Should be:

if [[ $input="X" ]]
  • This is not working! checkout my answer – OscarAkaElvis Dec 9 '16 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.