fbpx case Command Linux: Create Menus and Compare Values | Certificação Linux

case Command in Linux: Compare Values and Create Menus

📅 12/07/2021 ⏱ 2 min ✍️ Uira Ribeiro
Linuxcommands
case Command in Linux: Compare Values and Create Menus
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

The case command in Linux is a smart way to compare a value against multiple patterns.

If a match is found, it allows executing commands.

Each case is an expression that matches a pattern.

The operator ")" ends a pattern list and starts a command list.

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

At the end of the case, you must end with the esac statement (case backwards).

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

#!/bin/bashID=$(id -u)case "$ID" in   0)      echo "Você é o root.";      echo "Parabens!"   ;;   1000)      echo "Você é o Uirá."   ;;   100[1-9])      echo "Vocé é outro usuário"esacecho "fim";

If the value of variable ID is 0, it will print a congratulations message. If it equals 1000, it prints "you are Uirá". If it's between 1001 and 1009, it prints "You are another user".

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

$ ./meucase Você é o Uirá.fim

If executed as root:

$ sudo ./meucase Você é o root.Parabens!fim

The case is better than using the "if" command multiple times to compare something against multiple patterns.

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

Like it? Share

Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp