0

I'm going to create a script that should print "foo" or "bar" when a user's input is "foo" then print "bar" or when the user's input is "bar" then print "foo", otherwise show "invalid string". Here's the script which I'm working on:

foo=$x
bar=$y
val=$val
echo "enter the val = $val "
read $val
if [ "$val" = "$x" ]
then echo "bar"
elif [ "$val" = "$y" ] 
then echo "foo"
else echo "invalid string"
fi

I'm new to scripting so I don't know too much.

3

I think this is what you need:

#!/bin/bash

foo="foo"
bar="bar"

val=""

read -p "Enter the var: " val 

if [ "$val" == "$foo" ]; then
    echo "$bar"
else
    if [ "$val" == "$bar" ]; then
        echo "$foo"
    else
        echo "Invalid string"
    fi
fi

You can replace the if...else block for a case (this comes in handy when the possible options are too many):

case "$val" in
    "$foo")
        echo "$bar"
        ;;
    "$bar")
        echo "$foo"
        ;;
    *)
        echo "Invalid string"
        ;;
esac

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.