{"id":3779,"date":"2024-01-28T02:03:00","date_gmt":"2024-01-28T07:03:00","guid":{"rendered":"https:\/\/www.both.org\/?p=3779"},"modified":"2024-01-21T15:40:31","modified_gmt":"2024-01-21T20:40:31","slug":"using-logical-operators-on-the-bash-command-line","status":"publish","type":"post","link":"https:\/\/www.both.org\/?p=3779","title":{"rendered":"Using logical operators on the Bash command line"},"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=\"3779\" 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<h2 class=\"wp-block-heading\">Add powerful logic to the command line with control operators in compound commands.<\/h2>\n\n\n\n<p>Simple compound commands\u2014such as stringing several commands together in a sequence on the command line\u2014are used often on the Bash command line ans in Bash scripts. Such commands are separated by semicolons, which define the end of a command. To create a simple series of shell commands on a single line, simply separate each command using a semicolon, like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>command1 ; command2 ; command3 ; command4 ; <\/code><\/pre>\n\n\n\n<p>You don&#8217;t need to add a final semicolon because pressing the Enter key implies the end of the final command, but it&#8217;s fine to add&nbsp;it for consistency.<\/p>\n\n\n\n<p>All the commands will run without a problem\u2014as long as no error occurs. But what happens if an error happens? We can anticipate and allow for errors using the <strong>&amp;&amp;<\/strong> and <strong>||<\/strong> control operators built into Bash. These two control operators provide some flow control and enable us to alter the code-execution sequence. The semicolon and the <strong>newline<\/strong> character are also considered to be Bash control operators.<\/p>\n\n\n\n<p>The <strong>&amp;&amp;<\/strong> operator simply says &#8220;if command1 is successful, then run command2.&#8221; If command1 fails for any reason, command2 won&#8217;t run. That syntax looks like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>command1 &amp;&amp; command2<\/code><\/pre>\n\n\n\n<p>This works because every command returns a code to the shell that indicates whether it completed successfully or failed during execution. By convention, a return code (RC) of 0 (zero) indicates success and any positive number indicates some type of failure. Some sysadmin tools just return a 1 to indicate any type of failure. However, many use other positive numerical codes to indicate the type of failure. Such additional information can be helpful in problem determination.<\/p>\n\n\n\n<p>The Bash shell&#8217;s <strong>$?<\/strong> variable can be checked very easily by a script, by the next command in a list of commands, or even directly by a sysadmin. Let&#8217;s look at RCs. We can run a simple command and immediately check the RC, which will always pertain to the last command that ran.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;student@studentvm1 ~]$ <strong>ll ; echo \"RC = $?\"<\/strong>\ntotal 284\n-rw-rw-r--  1 student student   130 Sep 15 16:21 ascii-program.sh\ndrwxrwxr-x  2 student student  4096 Nov 10 11:09 bin\n&lt;snip&gt;\ndrwxr-xr-x. 2 student student  4096 Aug 18 10:21 Videos\nRC = 0\n&#91;student@studentvm1 ~]$<\/code><\/pre>\n\n\n\n<p>This RC is 0, which means the command completed successfully. Now try the same command on a directory where we don&#8217;t have permissions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;student@studentvm1 ~]$ <strong>ll \/root ; echo \"RC = $?\"<\/strong>\nls: cannot open directory '\/root': Permission denied\nRC = 2\n&#91;student@studentvm1 ~]$<\/code><\/pre>\n\n\n\n<p>This RC&#8217;s meaning can be found in the <a href=\"http:\/\/man7.org\/linux\/man-pages\/man1\/ls.1.html\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>ls<\/strong> command&#8217;s man page<\/a>.<\/p>\n\n\n\n<p>Let&#8217;s try the <strong>&amp;&amp;<\/strong> control operator as it might be used in a command-line program. We&#8217;ll start with something simple: Create a new directory and, if that is successful, create a new file in it.<\/p>\n\n\n\n<p>We need a directory where we can create other directories. First, create a temporary directory in your home directory where you can do some testing.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;student@studentvm1 ~]$ <strong>cd ; mkdir testdir<\/strong><\/code><\/pre>\n\n\n\n<p>Create a new directory in <strong>~\/testdir<\/strong>, which should be empty because you just created it, and then create a new, empty file in that new directory. The following command will do those tasks.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;student@studentvm1 ~]$ <strong>mkdir ~\/testdir\/testdir2 &amp;&amp; touch ~\/testdir\/testdir2\/testfile1 <\/strong>\n&#91;student@studentvm1 ~]$ <strong>ll ~\/testdir\/testdir2\/<\/strong>\ntotal 0\n-rw-rw-r-- 1 student student 0 Nov 12 14:13 testfile1\n&#91;student@studentvm1 ~]$<\/code><\/pre>\n\n\n\n<p>We know everything worked as it should because the <strong>testdir<\/strong> directory is accessible and writable. Change the permissions on <strong>testdir<\/strong> so it is no longer accessible to the user <strong>student<\/strong>&nbsp;as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;student@studentvm1 ~]$ <strong>chmod 076 testdir ; ll | grep testdir<\/strong>\nd---rwxrw-. 3 student student  4096 Nov 12 14:13 testdir\n&#91;student@studentvm1 ~]$<\/code><\/pre>\n\n\n\n<p>Using the <strong>grep<\/strong> command after the long list (<strong>ll<\/strong>) shows the listing for <strong>testdir<\/strong>. You can see that the user <strong>student<\/strong> no longer has access to the <strong>testdir<\/strong> directory.&nbsp;Now let&#8217;s run almost the same command&nbsp;as before but change it to create a different directory name inside <strong>testdir<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;student@studentvm1 ~]$ <strong>mkdir ~\/testdir\/testdir3 &amp;&amp; touch ~\/testdir\/testdir3\/testfile1 <\/strong>\nmkdir: cannot create directory \u2018\/home\/student\/testdir\/testdir3\u2019: Permission denied\n&#91;student@studentvm1 ~]$<\/code><\/pre>\n\n\n\n<p>Although we received an error message, using the <strong>&amp;&amp;<\/strong> control operator prevents the <strong>touch<\/strong> command from running because there was an error in creating <strong>testdir3<\/strong>. This type of command-line logical flow control can prevent errors from compounding and making a real mess of things. But let&#8217;s make it a little more complicated.<\/p>\n\n\n\n<p>The <strong>||<\/strong> control operator allows us to add another command that executes when the initial program statement returns a code larger than zero.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;student@studentvm1 ~]$ <strong>mkdir ~\/testdir\/testdir3 &amp;&amp; touch ~\/testdir\/testdir3\/testfile1 || echo \"An error occurred while creating the directory.\"<\/strong>\nmkdir: cannot create directory \u2018\/home\/student\/testdir\/testdir3\u2019: Permission denied\nAn error occurred while creating the directory.\n&#91;student@studentvm1 ~]$ <\/code><\/pre>\n\n\n\n<p>Our compound command syntax using flow control takes this general form when we use the <strong>&amp;&amp;<\/strong> and <strong>||<\/strong> control operators:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>preceding commands ; command1 &amp;&amp; command2 || command3 ; following commands<\/code><\/pre>\n\n\n\n<p>The compound command using the control operators may be preceded and followed by other commands that can be related to the ones in the flow-control section but which are unaffected by the flow control. All of those commands will execute without regard to anything that takes place inside the flow-control compound command.<\/p>\n\n\n\n<p>These flow-control operators can make working at the command line more efficient by handling decisions and letting us know when a problem has occurred. I use them directly on the command line as well as in scripts.<\/p>\n\n\n\n<p>You can clean up as the root user to delete the directory and its contents.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;root@studentvm1 ~]# <strong>rm -rf \/home\/student\/testdir<\/strong><\/code><\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Add powerful logic to the command line with control operators in compound commands.<\/p>\n","protected":false},"author":2,"featured_media":2725,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","footnotes":""},"categories":[149,98,100],"tags":[235,236],"class_list":["post-3779","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bash","category-code","category-command-line","tag-control-operators","tag-logical-operators"],"modified_by":"David Both","_links":{"self":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/3779","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\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3779"}],"version-history":[{"count":8,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/3779\/revisions"}],"predecessor-version":[{"id":3787,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/3779\/revisions\/3787"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/media\/2725"}],"wp:attachment":[{"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3779"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3779"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3779"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}