Skip to content

Linux case command (compare values)

The case command in Linux is an intelligent way to compare the value of something with various standards.

If an occurrence is positive, it allows commands to be executed.

Each case is an expression that corresponds to a pattern.

The ”)” operator ends a list of patterns and starts a list of commands.

What separates one pattern from another is ”;;”.

At the end of the case, you must finish with the esac instruction (case on the contrary).

Example of a script that, depending on the user’s UID, prints a different message:

#! /bin/bash <br></br>ID=$ (id -u) <br></br>case “$ID” in <br></br>0) <br></br>echo “You are the root.” ; <br></br>echo “Congratulations!” <br></br>;; <br></br>1000) <br></br>echo “You are Uira.”

;;
100 [1-9])
echo “You are another user”
esac
echo “end”; If the value of the ID variable is 0, it will print a congratulations message. If it is equal to 1000, print “you are Uira”. If it’s between 1001 and 1009, print “You’re another user.

If executed with the user uira, who has a UID equal to 1000:

$. /meucase <br></br>You are Uira.

End If run as root:

$ I sweat. /mycase <br></br>You are root. <br></br>Congratulations!

End The case is better than using the “if” command several times to compare something with various patterns.

Learn much more about Linux in our online course. You can register here. If you already have an account, or want to create one, just log in or create your user here.

Did you like it?

Share