How do I know if a variable is set in Bash? For example, how do I check if the user gave the first parameter to a function? function a { # if $1 is set ? }

In Bash, you can check if a variable is set using conditional statements and the -z test operator, which checks if a variable is empty (has zero length). To check if the user provided the first parameter to a function, you can use an if statement with the -z operator. Here's how you can do it:

function a {
    if [ -z "$1" ]; then
        echo "First parameter is not provided."
    else
        echo "First parameter is: $1"
    fi
}

a "Hello"

In this example, the a function checks if the first parameter ($1) is provided. If it's not provided (i.e., the length of $1 is zero), it prints a message indicating that the first parameter is not provided. Otherwise, it prints the value of the first parameter.

If you run the script with the provided example:

bash script.sh

Assuming the script is saved in a file named script.sh, the output will be:

sql

First parameter is: Hello

If you call the function without providing any arguments:

a

The output will be:

sql

First parameter is not provided.

This way, you can determine whether a variable (in this case, the function parameter) is set in Bash using the -z test operator in combination with conditional statements.

Comments