Using the bash case statement in shell scripting

Compiling from source

This section describes how to build ShellCheck from a source directory. ShellCheck is written in Haskell and requires 2GB of RAM to compile.

Installing Cabal

ShellCheck is built and packaged using Cabal. Install the package from your system’s package manager (with e.g. , , , , or ).

On macOS (OS X), you can do a fast install of Cabal using brew, which takes a couple of minutes instead of more than 30 minutes if you try to compile it from source.

Verify that is installed and update its dependency list with

Compiling ShellCheck

this repository, and to the ShellCheck source directory to build/install:

Or if you intend to run the tests:

This will compile ShellCheck and install it to your directory.

Add this directory to your (for bash, add this to your ):

export PATH="$HOME/.cabal/bin:$PATH"

Log out and in again, and verify that your PATH is set up correctly:

$ which shellcheck
~/.cabal/bin/shellcheck

On native Windows, the should already be set up, but the system
may use a legacy codepage. In , and Powershell ISE,
make sure to use a TrueType font, not a Raster font, and set the active
codepage to UTF-8 (65001) with :

chcp 65001

In Powershell ISE, you may need to additionally update the output encoding:

::OutputEncoding = ::UTF8

BASH Case Statement Termination Operators

As mentioned above, there are three different operators available when terminating a pattern clause.

  • The double semi-colon ‘;;’ will stop attempting to match patterns after the first match is found.
  • The semi-colon ampersand ‘;&’ will run the command associated with the next clause. This will happen whether there is a match on the following clause or not.
  • The double semi-colon ampersand ‘;;&’ will test the patterns in the rest of the clauses and only execute the command if there is a match.

The clause termination operators work in conjunction with each other. For more information on how they work see our Bash case statement video tutorial.

7.3.1. Simplified conditions

Nested if statements might be nice, but as soon as you are confronted with a couple of different possible actions to take, they tend to confuse. For the more complex conditionals, use the case syntax:

case EXPRESSION in CASE1) COMMAND-LIST;; CASE2) COMMAND-LIST;; … CASEN) COMMAND-LIST;; esac

Each case is an expression matching a pattern. The commands in the COMMAND-LIST for the first match are executed. The «|» symbol is used for separating multiple patterns, and the «)» operator terminates a pattern list. Each case plus its according commands are called a clause. Each clause must be terminated with «;;». Each case statement is ended with the esac statement.

In the example, we demonstrate use of cases for sending a more selective warning message with the disktest.sh script:

anny ~/testdir> cat disktest.sh
#!/bin/bash

# This script does a very simple test for checking disk space.

space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 | cut -d "%" -f1 -`

case $space in
*)
  Message="All is quiet."
  ;;
*)
  Message="Start thinking about cleaning out some stuff.  There's a partition that is $space % full."
  ;;
9)
  Message="Better hurry with that new disk...  One partition is $space % full."
  ;;
99)
  Message="I'm drowning here!  There's a partition at $space %!"
  ;;
*)
  Message="I seem to be running with an nonexistent amount of disk space..."
  ;;
esac

echo $Message | mail -s "disk report `date`" anny

anny ~/testdir>
You have new mail.

anny ~/testdir> tail -16 /var/spool/mail/anny
From anny@octarine Tue Jan 14 22:10:47 2003
Return-Path: <anny@octarine>
Received: from octarine (localhost )
        by octarine (8.12.5/8.12.5) with ESMTP id h0ELAlBG020414
        for <anny@octarine>; Tue, 14 Jan 2003 22:10:47 +0100
Received: (from anny@localhost)
        by octarine (8.12.5/8.12.5/Submit) id h0ELAltn020413
        for anny; Tue, 14 Jan 2003 22:10:47 +0100
Date: Tue, 14 Jan 2003 22:10:47 +0100
From: Anny <anny@octarine>
Message-Id: <200301142110.h0ELAltn020413@octarine>
To: anny@octarine
Subject: disk report Tue Jan 14 22:10:47 CET 2003

Start thinking about cleaning out some stuff.  There's a partition that is 87 % full.

anny ~/testdir>

Of course you could have opened your mail program to check the results; this is just to demonstrate that the script sends a decent mail with «To:», «Subject:» and «From:» header lines.

Синтаксис описания case

Оператор case имеет следующую форму:

case EXPRESSION in

  PATTERN_1)
    STATEMENTS
    ;;

  PATTERN_2)
    STATEMENTS
    ;;

  PATTERN_N)
    STATEMENTS
    ;;

  *)
    STATEMENTS
    ;;
esac
  • Каждый оператор case начинается с ключевого слова case, за которым следует выражение case и ключевое слово in. Утверждение заканчивается ключевым словом esac.
  • Вы можете использовать несколько шаблонов, разделенных оператором |. Оператор ) завершает список шаблонов.
  • Шаблон может иметь специальные символы.
  • Шаблон и связанные с ним команды называются предложениями.
  • Каждый пункт должен заканчиваться на ;;.
  • Команды, соответствующие первому шаблону, который соответствует выражению, выполняются.
  • Обычной практикой является использование подстановочного знака звездочки ( *) в качестве окончательного шаблона для определения регистра по умолчанию. Этот шаблон всегда будет совпадать.
  • Если не найдено ни одного шаблона, возвращаемый статус равен нулю. В противном случае возвращаемый статус – это статус завершения выполненных команд.

Installing

The easiest way to install ShellCheck locally is through your package manager.

On systems with Cabal (installs to ):

On systems with Stack (installs to ):

On Debian based distros:

On Arch Linux based distros:

On Gentoo based distros:

On EPEL based distros:

On Fedora based distros:

On FreeBSD:

On macOS (OS X) with Homebrew:

On OpenBSD:

On openSUSE

On Solus:

C:\> choco install shellcheck
C:\> scoop install shellcheck

From Snap Store:

From Docker Hub:

docker run --rm -v "$PWD:/mnt" koalaman/shellcheck:stable myscript
# Or :v0.4.7 for that version, or :latest for daily builds

or use if you want a larger Alpine Linux based image to extend. It works exactly like a regular Alpine image, but has shellcheck preinstalled.

nix-env -iA nixpkgs.shellcheck

Alternatively, you can download pre-compiled binaries for the latest release here:

  • Linux, x86_64 (statically linked)
  • Linux, armv6hf, i.e. Raspberry Pi (statically linked)
  • Linux, aarch64 aka ARM64 (statically linked)
  • macOS, x86_64
  • Windows, x86

or see the GitHub Releases for other releases
(including the latest meta-release for daily git builds).

Distro packages already come with a page. If you are building from source, it can be installed with:

pandoc -s -f markdown-smart -t man shellcheck.1.md -o shellcheck.1
sudo mv shellcheck.1 /usr/share/man/man1

Travis CI

Travis CI has now integrated ShellCheck by default, so you don’t need to manually install it.

If you still want to do so in order to upgrade at your leisure or ensure you’re
using the latest release, follow the steps below to install a binary version.

Installing a pre-compiled binary

The pre-compiled binaries come in files. To decompress them, make sure
is installed.
On Debian/Ubuntu/Mint, you can .
On Redhat/Fedora/CentOS, .

A simple installer may do something like:

scversion="stable" # or "v0.4.7", or "latest"
wget -qO- "https://github.com/koalaman/shellcheck/releases/download/${scversion?}/shellcheck-${scversion?}.linux.x86_64.tar.xz" | tar -xJv
cp "shellcheck-${scversion}/shellcheck" /usr/bin/
shellcheck --version

4 ответы

Из руководства bash: «Если зарезервированное слово! Предшествует
конвейеру, статус выхода этого конвейера является логическим
отрицанием статуса выхода»

Вы неправильно читаете грамматику. Что говорит грамматика, так
это то, что вы можете положить! перед трубопроводом, а не заменить
| с!.

6

Восклицательный знак только логически меняет обратный код
команды/конвейера (см., Например, Руководство Bash ):

Код возврата конвейера (обычно) — это только код возврата
последней команды, поэтому перебор инвертирует:

4

Определение конвейера one или более команд означает,
что одна команда также является конвейером, хотя она и не включает
в себя канал. Преимущество состоит в том, что как
оператор отрицания не обязательно должен быть определен отдельно
для команд и конвейеров; его нужно только определить как применение
к конвейеру.

В , отменяет статус
выхода всего конвейера, а не только одну команду
. Статус выхода для конвейера по умолчанию — это статус выхода из
самой правой команды.

Likewise, a list is one more pipelines joined by
, , , or
. Thus, a single pipeline is also a list, and a
single command is also a list. Then, when a command like
is defined as taking a list between the
and keywords, this automatically
includes single commands and single pipelines as part of the
definition of a command.

  • A list consisting of two pipelines (one of which only consists
    of one command):

  • A list consisting of a single pipeline:

  • A list consisting of single pipeline (which itself contains only
    a single command):

2

Несколько пунктов, чтобы добавить к тому, что другие ответы
сказали:

  • As noted (indirectly) by , the operator is defined as an optional
    prefix to the syntactic element, rather than to
    .  This has the consequence that you
    cannot say

    or

    You can only negate the exit status of an “entire
    pipeline”.  As chepner pointed out, a “pipeline” can be a
    single command, so you can do things like

    but that’s silly.  The before
    does nothing whatsoever; the
    before affects only the value of
    at the end of the command, and the other two can be eliminated by
    exchanging the AND and the OR:

    Similarly, can be replaced with
    .

  • A preceded by a becomes a — a different syntactic
    element.  Therefore, it is not valid to say

    unlike arithmetic expansion, where things like
    and
    are valid.

  • Be advised that defines the same grammar, but uses different element
    names.  The BNF in the question appears in POSIX as

    where is a with the value
    .

1

Examples

Another one of my stupid examples…

printf '%s ' 'Which fruit do you like most?'
read -${BASH_VERSION+e}r fruit

case $fruit in
    apple)
        echo 'Mmmmh... I like those!'
        ;;
    banana)
        echo 'Hm, a bit awry, no?'
        ;;
    orange|tangerine)
        echo $'Eeeks! I don\'t like those!\nGo away!'
        exit 1
        ;;
    *)
        echo "Unknown fruit - sure it isn't toxic?"
esac

Here’s a practical example showing a common pattern involving a statement. If the first argument is one of a valid set of alternatives, then perform some sysfs operations under Linux to control a video card’s power profile. Otherwise, show a usage synopsis, and print the current power profile and GPU temperature.

# Set radeon power management
function clk {
	typeset base=sysclassdrmcard0device
	 -r ${base}hwmonhwmon0temp1_input && -r ${base}power_profile  || return 1
 
	case $1 in
		low|high|default)
			printf '%s\n' "temp: $(<${base}/hwmon/hwmon0/temp1_input)C" "old profile: $(<${base}/power_profile)"
			echo "$1" >${base}power_profile
			echo "new profile: $(<${base}/power_profile)"
			;;
		*)
			echo "Usage: $FUNCNAME "
			printf '%s\n' "temp: $(<${base}/hwmon/hwmon0/temp1_input)C" "current profile: $(<${base}/power_profile)"
	esac
}

A template for experiments with logic, showing shared code between blocks using , and the non-short-circuiting operator:

#!/usr/bin/env bash
 
f() {
    local -a "$@"
    local x
 
    for x; do
        case $x in
            $1)
                local "$x"'+=(1)' ;;&
            $2)
                local "$x"'+=(2)' ;&
            $3)
                local "$x"'+=(3)' ;;
            $1|$2)
                local "$x"'+=(4)'
        esac
        IFS=, local -a "$x"'=("${x}: ${'"$x"'}")'
    done
 
    for x; do
        echo "${!x}"
    done
}
 
f a b c
 
# output:
# a: 1,4
# b: 2,3
# c: 3

Case Statement – Basic Syntax:

Case Statement — Basic Syntax

case expression inpattern1 )statements ;;pattern2 )statements ;;…esac

Key points:

  • Every case statement starts with case keyword.
  • The case keyword will be followed by the case expression and in keyword.
  • The esac keyword is always required to indicate the end of the case statement.
  • You have to use ‘ | ‘ operator while using multiple patterns.
  • A pattern and its related commands are recognized as a clause. You must include ‘ ;; ‘ at the end of each clause.
  • The pattern list needs to be terminated by the ‘ ) ‘ operator. The pattern can include special characters.
  • If a pattern matches the expression, statements corresponding to that pattern will be executed.
  • After the first match, the case stops with the exit status of the last statement that was executed.
  • If there is no match, the exit status of case is zero.
  • To describe the default case, it is a common practice to use the wildcard asterisk symbol ( * ) as a closing pattern. This pattern will match all the time.

Changing the case of text in variables

It is often useful to change the case of a variable. A hostname may need converting, or maybe you
want to be sure to get somebody’s name properly capitalised: , as opposed to
, or even .

The old way to do this was with the command, either in the GNU form (which understands keywords :lower: and :upper:), like this:

echo $name | tr '' ''

Or in the non-GNU form, using a range, like this:

echo $name | tr '' ''

Either way, this was a bit ugly, and a bit of a hassle.

Bash provides an alternative method. From the page, it isn’t very clear what it
does, so many people are quite unaware of this useful facility.

The operator converts to uppercase, while converts to lowercase.

If you double-up the operators, ie, or , it applies to the whole string; otherwise,
it applies only to the first letter (that isn’t absolutely correct — see «Advanced Usage» below — but for most uses, it’s an adequate description).

For example, if you want to ensure that a name read in is all in lowercase, you can do this:

#!/bin/bash
read -p "What is your first name? " firstname
firstname=${firstname,,}
echo "Hello, ${firstname}."

When run, this will take any input you give it, and convert it all to lowercase:

$ ./case.sh 
What is your first name? steve
Hello, steve.
$ ./case.sh 
What is your first name? STEVE
Hello, steve.
$ ./case.sh 
What is your first name? StEvE
Hello, steve.
$ 

You can then take this further, by using the single operator. This will convert just the first letter to uppercase
(and of course a single would convert it to lowercase).

#!/bin/bash
read -p "What is your first name? " firstname
firstname=${firstname,,}
firstname=${firstname^}
echo "Hello, ${firstname}."

When you run this, it first converts the whole thing to lowercase, as before, but then converts the first letter to uppercase,
to fit with the standard convention of a name having an initial uppercase character, followed by lowercase:

$ ./case.sh 
What is your first name? steve
Hello, Steve.
$ ./case.sh 
What is your first name? STEVE
Hello, Steve.
$ ./case.sh 
What is your first name? StEvE
Hello, Steve.
$ 

Case Statement Terminator Example

In the above example we were able to find which series a Star Trek character is from using a case statement. BUT, what if a character was in multiple series? If you are a Star Trek fan you are already saying «Worf was in The Next Generation too!». This is where the clause terminators come in handy. We can use the double semi-colon ampersand ‘;;&’ terminator to allow the script to continue searching the next clause for additional matches.

Here is our updated script, notice the ampersand sign is now terminating the clauses. We also added a new clause for characters from TNG.

Here is the updated script in action.

How to use

There are a number of ways to use ShellCheck!

In your editor

You can see ShellCheck suggestions directly in a variety of editors.

Vim, through ALE, Neomake, or Syntastic:

.

Emacs, through Flycheck or Flymake:

.

  • Sublime, through SublimeLinter.

  • Atom, through Linter.

  • VSCode, through vscode-shellcheck.

  • Most other editors, through .

In your build or test suites

While ShellCheck is mostly intended for interactive use, it can easily be added to builds or test suites.
It makes canonical use of exit codes, so you can just add a command as part of the process.

For example, in a Makefile:

check-scripts:
    # Fail if any of these files have warnings
    shellcheck myscripts/*.sh

or in a Travis CI file:

script:
  # Fail if any of these files have warnings
  - shellcheck myscripts/*.sh

Services and platforms that have ShellCheck pre-installed and ready to use:

  • Github(only Linux)

Services and platforms with third party plugins:

SonarQube through sonar-shellcheck-plugin

It’s a good idea to manually install a specific ShellCheck version regardless. This avoids
any surprise build breaks when a new version with new warnings is published.

For customized filtering or reporting, ShellCheck can output simple JSON, CheckStyle compatible XML,
GCC compatible warnings as well as human readable text (with or without ANSI colors). See the
Integration wiki page for more documentation.

Examples of Case Statement:

Let’s look out some examples to understand the usage of the case statement in Bash.

Example 1:

Add the following code in your Text Editor and then save it as case1.sh script.

Example 1

read -p “Enter your choice [yes/no]: ” choice

case $choice inyes)echo “Welcome”echo “You typed: Yes”;;no)echo “Oops”echo “You typed: No”;;*)echo “Invalid Input”;;esac

Run the script:

$ bash case1.sh

Output:

Output 1

Enter your choice [yes/no]: yesWelcomeYou typed: Yes

Output 2

Enter your choice [yes/no]: noOopsYou typed: No

Output 3

Enter your choice [yes/no]: yInvalid Input

Example 2:

The following shell script demonstrates the usage of multiple patterns.

Add the following code in your Text Editor and then save it as case2.sh script.

Example 2

echo -n “Enter the name of a car: “read CAR

echo -n “The price of $CAR car is “

case $CAR in

Audi | Ford)echo “32 Lakhs”;;

BMW)echo “90 Lakhs”;;

Ferrari | Jaguar)echo “3 Crores”;;

*)echo -n “unknown”;;esac

  • The above script will ask you to enter the name of a car. For example, if you type “BMW” it will match the third pattern and the echo command in that clause will be executed.
  • If you enter the car name that does not match any other pattern except the default wildcard asterisk symbol, the echo command inside the default clause will be executed

Run the script:

$ bash case2.sh

Output:

Output 1

Enter the name of a car: JaguarThe price of Jaguar car is 3 Crores

Output 2

Enter the name of a car: ChevroletThe price of Chevrolet car is unknown

Output 3

Enter the name of a car: BMWThe price of BMW car is 90 Lakhs

Advanced Usage

There is another feature to this transformation, although it is hard to find a use for it. You can provide a single-character pattern to match.
If you use the single or , only the first character in the string (note — this is not the first matching character,
but the first character, whatever it may be) is compared, and converted if it matches. If you use or then all
matching characters are converted.

One example would be:

#!/bin/bash
read -p "Enter some lowercase text: " text
echo "I have highlighted the letter 'E' for you:"
echo ${text^^e}
$ 

You could run this, and highlight the letter ‘E’ any time it is mentioned, by capitalising it:

$ ./case2.sh 
Enter some lowercase text: abcdefghiabcdefghi
I have highlighted the letter 'E' for you:
abcdEfghiabcdEfghi
$

This could be made more useful, by making the highlighted letter itself variable:

#!/bin/bash
read -p "Enter some lowercase text: " text
read -p "Which letter do you want to highlight?: " highlight
echo "I have highlighted that letter for you:"
echo ${text^^$highlight}

When run, this would capitalise whichever letter you asked it to:

$ ./case2.sh 
Enter some lowercase text: abcdefghiabcdefghi
Which letter do you want to highlight?: d
I have highlighted that letter for you:
abcDefghiabcDefghi
$ ./case2.sh 
Enter some lowercase text: abcdefghiabcdefghi
Which letter do you want to highlight?: g
I have highlighted that letter for you:
abcdefGhiabcdefGhi
$ 

Bash Case Statement Example

Here is an example of a Bash case statement used in a shell script. In this example we will create a case statement that will tell us which Star Trek series a character was in. We will use a read statement to prompt for user input.

If you read that script carefully you will notice that «Seven of Nine» is the only character that is wrapped in quotes. This is because she is the only character with spaces in her name. Wrapping the spaces in quotes allows the shell to treat the spaces as part of the pattern. There are several ways to deal with spaces or special characters in filenames or patterns.

Here is our example script in action.

Пример заявления case

Вот пример использования оператора case в bash-скрипте, который будет печатать официальный язык данной страны:

languages.sh

#!/bin/bash

echo -n "Введите название страны: "
read COUNTRY

echo -n "Официальный язык $COUNTRY это "

case $COUNTRY in

  Russia)
    echo -n "Russia"
    ;;

  Brazil)
    echo -n "Brazil"
    ;;

  Italy | "San Marino" | Switzerland | "Vatican City")
    echo -n "Italian"
    ;;

  *)
    echo -n "неизвестный"
    ;;
esac

Сохраните пользовательский скрипт в виде файла и запустите его из командной строки.

bash languages.sh

Скрипт попросит вас ввести страну. Например, если вы введете «Russia», она будет соответствовать первому шаблону, и команда echo в этом предложении будет выполнена.

Скрипт выведет следующий вывод:

Введите название страны: Russia
Официальный язык Russia это Russian

Если вы вводите страну, которая не соответствует ни одному другому шаблону, кроме подстановочного символа по умолчанию, скажем, Ukraine, скрипт выполнит команду echo внутри предложения по умолчанию.

Введите название страны: Ukraine
Официальный язык Ukraine is неизвестный

Syntax

The syntax is as follows:

          case  $variable-name  in
                pattern1)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                pattern2)
     		    command1
                    ...
                    ....
                    commandN
                    ;;            
                patternN)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                *)              
          esac 

OR

          case  $variable-name  in
                pattern1|pattern2|pattern3)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                pattern4|pattern5|pattern6)
     		    command1
                    ...
                    ....
                    commandN
                    ;;            
                pattern7|pattern8|patternN)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                *)              
          esac 
  • The case statement allows you to easily check pattern (conditions) and then process a command-line if that condition evaluates to true.
  • In other words the $variable-name is compared against the patterns until a match is found.
  • *) acts as default and it is executed if no match is found.
  • The pattern can include wildcards.
  • You must include ;; at the end of each commandN. The shell executes all the statements up to the two semicolons that are next to each other.
  • The esac is always required to indicate end of case statement.

Example

Create a shell script called rental.sh:

#!/bin/bash

# if no command line arg given
# set rental to Unknown
if  -z $1 
then
  rental="*** Unknown vehicle ***"
elif  -n $1 
then
# otherwise make first arg as a rental
  rental=$1
fi

# use case statement to make decision for rental
case $rental in
   "car") echo "For $rental rental is Rs.20 per k/m.";;
   "van") echo "For $rental rental is Rs.10 per k/m.";;
   "jeep") echo "For $rental rental is Rs.5 per k/m.";;
   "bicycle") echo "For $rental rental 20 paisa per k/m.";;
   "enfield") echo "For $rental rental Rs.3  per k/m.";;
   "thunderbird") echo "For $rental rental Rs.5 per k/m.";;
   *) echo "Sorry, I can not get a $rental rental  for you!";;
esac

Save and close the file. Run it as follows:

chmod +x rental.sh
./rental.sh 
./rental.sh jeep
./rental.sh enfield
./rental.sh bike

Sample outputs:

Sorry, I can not get a *** Unknown vehicle *** rental  for you!
For jeep rental is Rs.5 per k/m.
For enfield rental Rs.3  per k/m.
Sorry, I can not get a bike rental  for you!

The case statement first checks $rental against each option for a match. If it matches «car», the echo command will display rental for car. If it matches «van», the echo command will display rental for van and so on. If it matches nothing i.e. * (default option), an appropriate warning message is printed.

Using Multiple Patterns

#!/bin/bash
NOW=$(date +"%a")
case $NOW in
	Mon)	
		echo "Full backup";;
	Tue|Wed|Thu|Fri)
		echo "Partial backup";;
	Sat|Sun)	
		echo "No backup";;
	*) ;;
esac

The following shell script demonstrate the concept of command line parameters processing using the case statement (casecmdargs.sh):

#!/bin/bash
OPT=$1   # option
FILE=$2  # filename

# test -e and -E command line args matching
case $OPT in
  -e|-E) 
  	echo "Editing $2 file..." 
        # make sure filename is passed else an error displayed   
  	 -z $FILE  && { echo "File name missing"; exit 1; } || vi $FILE	
  	;;
  -c|-C) 
  	echo "Displaying $2 file..." 
  	 -z $FILE  && { echo "File name missing"; exit 1; } || cat $FILE	
  	;;
  -d|-D) 
  	echo "Today is $(date)" 
  	;;
   *) 
    echo "Bad argument!" 
    echo "Usage: $0 -ecd filename"
    echo "	-e file : Edit file."
    echo "	-c file : Display file."
    echo "	-d      : Display current date and time."	
    ;;
esac

Run it as follows:

chmod +x casecmdargs.sh
./casecmdargs.sh
./casecmdargs.sh -e /tmp/file
./casecmdargs.sh -E /tmp/file
./casecmdargs.sh -e 
./casecmdargs.sh -D

Creating a backup script

Create a backup script called allinonebackup.sh:

#!/bin/bash
# A shell script to backup mysql, webserver and files to tape
opt=$1
case $opt in
        sql)
                echo "Running mysql backup using mysqldump tool..."
                ;;
        sync)
                echo "Running backup using rsync tool..."
                ;;
        tar)
                echo "Running tape backup using tar tool..."
                ;;
        *)
        	    echo "Backup shell script utility"
                echo "Usage: $0 {sql|sync|tar}"
                echo "	sql  : Run mySQL backup utility."
                echo "	sync : Run web server backup utility."	
                echo "	tar  : Run tape backup utility."	;;
esac

Save and close the file. Run it as follows:

chmod +x allinonebackup.sh
# run sql backup
./allinonebackup.sh sql
# Dump file system using tape device
./allinonebackup.sh tar
# however, the following will fail as patterns are case sensitive
# you must use command line argument tar and not TAR, Tar, TaR etc. 
./allinonebackup.sh TAR

Basic Syntax of Case Statements

The case statement is much different than it’s cousin the if statement. Below is an example of the basic syntax followed by a brief explanation.

Let’s inspect the syntax line by line.

The above line starts the case statement by invoking case. It is followed by WORD, which is the word or expression you will try to match in the patterns that follow. This is usually a variable.

The second line (shown above), shows the pattern you are testing for a match. You can separate several patterns with the pipe ‘|’ , as shown in the third line. The pattern list is then terminated with the end parenthesis ‘)’. You follow the patterns with the command you want to run, if your word matches those patterns. Each clause is terminated with a double semi-colon ‘;;’, a semi-colon then ampersand ‘;&’, or double semi-colon then ampersand ‘;;&’. We will outline the different operators (clause terminators?) later in the article.

The line above is the catch-all line, or default case. The asterisks ‘*’ wildcard will match any pattern. Using a catch all is optional.

You end the case statement with the word case backwards, similar to how fi closes an if statement.

Etc

Society

Quotes

Bulletin:

History:

Classic books:

Most popular humor pages:

The Last but not Least Technology is dominated by
two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt.
Ph.D

Copyright 1996-2020 by Softpanorama Society. www.softpanorama.org
was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP)
in the author free time and without any remuneration. This document is an industrial compilation designed and created exclusively
for educational use
and is distributed under the Softpanorama Content License.
Original materials copyright belong
to respective owners. Quotes are made for educational purposes only
in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains
copyrighted material the use of which has not always been specifically
authorized by the copyright owner. We are making such material available
to advance understanding of computer science, IT technology, economic, scientific, and social
issues. We believe this constitutes a ‘fair use’ of any such
copyrighted material as provided by section 107 of the US Copyright Law according to which
such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free)
site written by people for whom English is not a native language.
Grammar and spelling errors should
be expected. The site contain some broken links as it develops like a living tree…

You can use PayPal to make a contribution, supporting development
of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or
referenced source) and are
not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with.
We do not warrant the correctness
of the information provided or its fitness for any purpose.
The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be
tracked by Google please disable Javascript for this site. This site is perfectly usable without
Javascript.

Last modified:
September 10, 2019

Description

The -statement can execute commands based on a pattern matching decision. The word is matched against every pattern and on a match, the associated is executed. Every commandlist is terminated by . This rule is optional for the very last commandlist (i.e., you can omit the before the ). Every is separated from it’s associated by a , and is optionally preceded by a .

Bash 4 introduces two new action terminators. The classic behavior using is to execute only the list associated with the first matching pattern, then break out of the block. The terminator causes to also execute the next block without testing its pattern. The operator is like , except the case statement doesn’t terminate after executing the associated list — Bash just continues testing the next pattern as though the previous pattern didn’t match. Using these terminators, a statement can be configured to test against all patterns, or to share code between blocks, for example.

The word is expanded using tilde, parameter and variable expansion; arithmetic, command and process substitution; and quote removal. No word splitting, brace, or pathname expansion is done, which means you can leave expansions unquoted without problems:

var="test word"

case $var in
  ...
esac

This is similar to the behavior of the conditional expression command («new test command») (also no word splitting for expansions).

Unlike the C-case-statement, only the matching list and nothing else is executed. If more patterns match the word, only the first match is taken. (Note the comment about Bash v4 changes above.)

Multiple -delimited patterns can be specified for a single block. This is a POSIX-compatable equivalent to the extglob construct.

The statement is one of the most difficult commands to indent clearly, and people frequently ask about the most «correct» style. Just do your best — there are many variations of indenting style for and no real agreed-upon best practice.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *