{"id":4796,"date":"2024-04-14T03:00:00","date_gmt":"2024-04-14T07:00:00","guid":{"rendered":"https:\/\/www.both.org\/?p=4796"},"modified":"2024-04-05T14:39:27","modified_gmt":"2024-04-05T18:39:27","slug":"learn-bash-by-writing-a-number-guessing-game","status":"publish","type":"post","link":"https:\/\/www.both.org\/?p=4796","title":{"rendered":"Learn Bash by writing a number guessing game"},"content":{"rendered":"<div class=\"pld-like-dislike-wrap pld-template-1\">\r\n    <div class=\"pld-like-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-like-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"4796\" data-trigger-type=\"like\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-up\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-like-count-wrap pld-count-wrap\">    <\/span>\r\n<\/div><\/div>\n<p>Whenever I try to learn a new language, whether it\u2019s a new shell scripting language or a new programming language to write larger programs, I focus on a few things: defining variables, writing statements, and evaluating expressions. Once I understand how to do those concepts, I can usually figure out the rest on my own. Most programming languages share some similarities, so learning the rest is usually a matter of working out the details.<\/p>\n\n\n\n<p>I like to write a few \u201ctest\u201d or \u201cscratch\u201d programs to practice a new programming language. One sample program I use frequently as an example is the classic \u201cguess the number\u201d program, where the computer picks a number in a range and prompts me to guess the secret number. This exercises how to assign values, how to write statements, and how to evaluate and compare values.<\/p>\n\n\n\n<p>If you\u2019d like to learn how to write shell scripts in Bash, you can use the \u201cguess the number\u201d program to practice Bash scripting.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"a-brief-introduction-to-bash\">A brief introduction to Bash<\/h2>\n\n\n\n<p>GNU&nbsp;<strong>Bash<\/strong>&nbsp;is the standard shell for most Linux system. Its name comes from the original Unix shell, which was just named&nbsp;<code>sh<\/code>. Later, Unix added support for other shells, including&nbsp;<code>ksh<\/code>&nbsp;for the Korn Shell, and&nbsp;<code>bsh<\/code>&nbsp;for the Bourne Shell. Bash is actually short for the \u201cBourne Again Shell,\u201d a play on the original \u201cBourne Shell\u201d name on older \u201cBig Unix\u201d systems.<\/p>\n\n\n\n<p>Bash supports all the features of&nbsp;<code>bsh<\/code>&nbsp;but adds several other useful features. Its backwards compatibility with classic Unix shells makes it a popular choice on many Linux systems.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"guess-the-number-in-bash\">Guess the number in Bash<\/h2>\n\n\n\n<p>To write a \u201cguess the number\u201d script in Bash, we need to do a few things:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Pick a random number from 1 to 100, and save it to a variable (<code>secret<\/code>)<\/li>\n\n\n\n<li>Enter a loop where the user enters their guess, and the script says if the guess is too high or too low<\/li>\n\n\n\n<li>Exit the loop when the user guesses the secret number<\/li>\n<\/ol>\n\n\n\n<p>To select a random value, you can use the\u00a0<code>$RANDOM<\/code>\u00a0internal variable. The name of the variable is actually\u00a0<code>RANDOM<\/code>\u00a0and you can reference the\u00a0<em>value<\/em>\u00a0of the variable with the dollar sign in front:\u00a0<code>$RANDOM<\/code>\u00a0will always generate a random number, usually a large number.<\/p>\n\n\n\n<p>You can use the \u201cmodulo\u201d arithmetic operator (<code>%<\/code>) to divide the random number by another number and get the&nbsp;<em>remainder<\/em>. For example,&nbsp;<code>21 % 10<\/code>&nbsp;is 1, because 21 divided by 10 is 2, with 1 left over. But&nbsp;<code>20 % 10<\/code>&nbsp;is 0, because 10 goes into 20 exactly twice, with nothing left over. That means&nbsp;<code>$RANDOM % 100<\/code>&nbsp;will give values between zero and 99. To make the secret number between 1 and 100, use&nbsp;<code>$RANDOM % 100 + 1<\/code>.<\/p>\n\n\n\n<p>Bash provides&nbsp;<em>arithmetic expansion<\/em>&nbsp;using the&nbsp;<code>$(( ))<\/code>&nbsp;notation, so use this to calculate a random number from 1 to 100 and save it in a new variable called&nbsp;<code>secret<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>secret=$(( $RANDOM % 100 + 1 ))<\/code><\/pre>\n\n\n\n<p>Next, set a variable to store the user\u2019s guess. We can initialize it to zero with:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>guess=0<\/code><\/pre>\n\n\n\n<p>To start a loop that will continue only if the user\u2019s guess is&nbsp;<em>not<\/em>&nbsp;equal to the secret number, use:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while &#91; \"0$guess\" -ne $secret ] ; do\n...\ndone<\/code><\/pre>\n\n\n\n<p>In this example, I\u2019ve used&nbsp;<code>\"0$guess<\/code>&nbsp;to prepend a zero in front of the user\u2019s guess, in case the user types a non-digit value like&nbsp;<code>m<\/code>. The&nbsp;<code>-ne<\/code>&nbsp;comparison test will only work with numbers, so&nbsp;<code>0m -ne 50<\/code>&nbsp;will test what we want: that the&nbsp;<em>number value<\/em>&nbsp;of 0 is&nbsp;<em>not equal<\/em>&nbsp;to 50, if the secret number was 50.<\/p>\n\n\n\n<p>Get values from the user with the&nbsp;<code>read<\/code>&nbsp;statement:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>read guess<\/code><\/pre>\n\n\n\n<p>You can test if one number is&nbsp;<em>less than<\/em>&nbsp;another using the&nbsp;<code>-lt<\/code>&nbsp;comparison, and&nbsp;<em>greater than<\/em>&nbsp;using the&nbsp;<code>-gt<\/code>&nbsp;test. You can use an&nbsp;<code>if<\/code>&nbsp;block in Bash to do each test, but a one-line shortcut uses&nbsp;<code>&amp;&amp;<\/code>&nbsp;to basically say \u201c<em>if this test on the left is true<\/em>&nbsp;then&nbsp;<em>do this task on the right<\/em>. For example, you could add two tests to print if the user\u2019s guess was too low or too high:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91; \"0$guess\" -lt $secret ] &amp;&amp; echo \"Too low\"\n&#91; \"0$guess\" -gt $secret ] &amp;&amp; echo \"Too high\"<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"putting-it-all-together\">Putting it all together<\/h2>\n\n\n\n<p>Let\u2019s combine what we\u2019ve learned about Bash scripting in this file, called&nbsp;<code>guess<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/bin\/bash\n\nsecret=$(( $RANDOM % 100 + 1 ))\n\nguess=0\necho \"Guess a number between 1 and 100\"\n\nwhile &#91; \"0$guess\" -ne $secret ] ; do\n    read guess\n    &#91; \"0$guess\" -lt $secret ] &amp;&amp; echo \"Too low\"\n    &#91; \"0$guess\" -gt $secret ] &amp;&amp; echo \"Too high\"\ndone\n\necho \"That's right!\"<\/code><\/pre>\n\n\n\n<p>I\u2019ve added an&nbsp;<code>echo<\/code>&nbsp;statement at the top to tell the user what the script will do, and another&nbsp;<code>echo<\/code>&nbsp;statement at the end to let the user know when they\u2019ve guessed the number.<\/p>\n\n\n\n<p>Make this script executable with the&nbsp;<code>chmod<\/code>&nbsp;command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ chmod +x guess<\/code><\/pre>\n\n\n\n<p>And now you can run your script whenever you want to play the \u201cguess the number\u201d game:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ .\/guess\nGuess a number between 1 and 100\n50\nToo high\n25\nToo low\n33\nToo high\n30\nToo high\n28\nToo high\n27\nThat's right!<\/code><\/pre>\n\n\n\n<p>Every time you run the script, the&nbsp;<code>$RANDOM<\/code>&nbsp;internal variable gives a new number, so you\u2019ll always have a random secret number between 1 and 100:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ .\/guess\nGuess a number between 1 and 100\n50\nToo low\n75\nToo low\n88\nToo high\n80\nToo low\n84\nThat's right!<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"learning-is-fun\">Learning is fun<\/h2>\n\n\n\n<p>This \u201cguess the number\u201d game is a great introductory program when learning a new programming language because it exercises several common programming concepts in a pretty straightforward way. By implementing this simple game in different programming languages, you can demonstrate some core concepts and compare details in each language.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learning a new programming language can be a fun exercise.<\/p>\n","protected":false},"author":33,"featured_media":4314,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","footnotes":""},"categories":[149,69,150],"tags":[151,147,91,152],"class_list":["post-4796","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bash","category-fun","category-programming","tag-bash","tag-fun","tag-linux","tag-programming"],"modified_by":"Jim Hall","_links":{"self":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/4796","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/users\/33"}],"replies":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4796"}],"version-history":[{"count":1,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/4796\/revisions"}],"predecessor-version":[{"id":4797,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/4796\/revisions\/4797"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/media\/4314"}],"wp:attachment":[{"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4796"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4796"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4796"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}