We can also use digits or numerical variables as the expression. Badly spelled months are caught by the default clause. We’ll run the script several times and show that it doesn’t matter if we use uppercase or lowercase./month.shīecause we told the script to ignore differences in uppercase and lowercase any month name spelled correctly is handled by one of the three main clauses. We saved this into a file called “month.sh”, and made it executable.
The default case catches badly spelled months. Multi-pattern clauses use the pipe symbol “|” as the separator. January | March | May | July | August | October | December)įebruary gets a clause to itself, and all the other months share two clauses according to whether they have 30 or 31 days in them.
It won’t matter if the input contains uppercase, lowercase, or a mixture of the two. To make the pattern matching case insensitive we use the shopt command with the -s nocasematch option. In this script, the user is prompted for the name of a month. There can only be three answers: 30 days, 31 days, or 28 or 29 days for February. So, although there are 12 months we only need three clauses. Here’s a script that tells you how many days there are in a month. If the expression matches any of those patterns the statements in that clause are executed.
#Mac bash for loop how to
RELATED: How to Use the chmod Command on Linux Using Multiple Patterns in a ClauseĪ really neat feature of case statements is you can use multiple patterns in each clause. We can shorten that type of case statement quite easily. That script works and it is easy to read, but it is long-winded and repetitive. Anything that doesn’t match one of the preceding clauses is ignored. However, you must use double quotes if the pattern contains spaces. Note that the patterns in the clauses don’t need to be wrapped in double quotes, but it doesn’t do any harm if they are. That means the DayName variable holds the string “Fri.” This is matched with the “Fri” pattern of the “Fri)” clause. The day the screenshot was taken happens to be a Friday. You’ll need to do that for all of the scripts you create as you work through this article. We’ll need to use the chmod command to make it executable. #!/bin/bashĬopy that text into an editor and save it as a file called “open.sh.” It uses the date command with the +"%a" format string to obtain the shortened day name. This script tells us the opening hours for an imaginary shop. If an expression isn’t matched with any of the other patterns in the case statement the default clause is executed.