Plant.Power Plant.Power - 5 months ago 15
Bash Question

Shell Script check if a string contains two in-parameters

I'm taking a intro to Linux and shell script course at Uni. Just came across a problem.

I need to make an if statement that controls if there is only 2 arguments and then write those out and if not return a warning string.

#!/bin/bash

echo "Please input two variables: "

read var

if var = ' '; then
echo var
else
echo "More or less than two arguments"
fi


This is what I have so far. I thought I could make the if statment look for a space in the string.

This is my first post here on StackExchange. So hello to all fellow StackExchangers out there :=)

Answer

What you can do is create an array out of your input and then check its length.

#!/bin/bash

echo "Please input two variables: "
read var

myArray=($var)

if [ ${#myArray[@]} -eq 2 ];
then
        echo ${myArray[*]}
else
        echo "More or less than two arguments"
fi

Values in bash arrays are separated by spaces, so when var gets expanded each word is created as a new array index.

Comments