{"id":183,"date":"2018-10-21T00:00:00","date_gmt":"2018-10-20T16:00:00","guid":{"rendered":"https:\/\/yeslq.com\/201810183.html"},"modified":"2019-05-07T10:43:39","modified_gmt":"2019-05-07T02:43:39","slug":"the-linux-command-line-flow-control_21","status":"publish","type":"post","link":"https:\/\/yeslq.com\/?p=183","title":{"rendered":"The Linux Command Line&#8212;Flow Control &#8211; Part 3"},"content":{"rendered":"<h1 style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif; font-weight: normal;\">\n<i style=\"font-size: x-small;\"><a href=\"http:\/\/linuxcommand.org\/tlcl.php\" style=\"color: #002740;\">The Linux Command Line&nbsp;<\/a><\/i><span style=\"font-size: xx-small;\">by William Shotts<\/span><\/h1>\n<div>\n<span style=\"font-size: xx-small;\"><br \/><\/span><\/div>\n<div>\n<span style=\"font-size: xx-small;\"><\/p>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nNow that you have learned about positional parameters, it is time to cover the remaining flow control statement,&nbsp;<a href=\"http:\/\/linuxcommand.org\/lc3_man_pages\/forh.html\" style=\"color: #002740;\">for<\/a>. Like&nbsp;while&nbsp;and&nbsp;until,&nbsp;for&nbsp;is used to construct loops.&nbsp;for&nbsp;works like this:<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">for variable in words; do\n    commands\ndone\n     \n<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nIn essence,&nbsp;for&nbsp;assigns a word from the list of words to the specified variable, executes the commands, and repeats this over and over until all the words have been used up. Here is an example:<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">#!\/bin\/bash\n\nfor i in word1 word2 word3; do\n    echo $i\ndone\n     \n<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nIn this example, the variable&nbsp;i&nbsp;is assigned the string &#8220;word1&#8221;, then the statement&nbsp;echo $i&nbsp;is executed, then the variable&nbsp;i&nbsp;is assigned the string &#8220;word2&#8221;, and the statement&nbsp;echo $i&nbsp;is executed, and so on, until all the words in the list of words have been assigned.<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nThe interesting thing about&nbsp;for&nbsp;is the many ways you can construct the list of words. All kinds of expansions can be used. In the next example, we will construct the list of words using command substitution:<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">#!\/bin\/bash\n\ncount=0\nfor i in $(cat ~\/.bash_profile); do\n    count=$((count + 1))\n    echo \"Word $count ($i) contains $(echo -n $i | wc -c) characters\"\ndone<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nHere we take the file&nbsp;.bash_profile&nbsp;and count the number of words in the file and the number of characters in each word.<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nSo what&#8217;s this got to do with positional parameters? Well, one of the features of&nbsp;for&nbsp;is that it can use the positional parameters as the list of words:<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">#!\/bin\/bash\n\nfor i in \"$@\"; do\n    echo $i\ndone<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nThe shell variable&nbsp;&#8220;$@&#8221;&nbsp;contains the list of command line arguments. This technique is often used to process a list of files on the command line. Here is a another example:<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">#!\/bin\/bash\n\nfor filename in \"$@\"; do\n    result=\n    if [ -f \"$filename\" ]; then\n        result=\"$filename is a regular file\"\n    else\n        if [ -d \"$filename\" ]; then\n            result=\"$filename is a directory\"\n        fi\n    fi\n    if [ -w \"$filename\" ]; then\n        result=\"$result and it is writable\"\n    else\n        result=\"$result and it is not writable\"\n    fi\n    echo \"$result\"\ndone<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nTry this script. Give it a list of files or a wildcard like &#8220;*&#8221; to see it work.<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nHere is another example script. This one compares the files in two directories and lists which files in the first directory are missing from the second.<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">#!\/bin\/bash\n\n# cmp_dir - program to compare two directories\n\n# Check for required arguments\nif [ $# -ne 2 ]; then\n    echo \"usage: $0 directory_1 directory_2\" 1&gt;&amp;2\n    exit 1\nfi\n\n# Make sure both arguments are directories\nif [ ! -d $1 ]; then\n    echo \"$1 is not a directory!\" 1&gt;&amp;2\n    exit 1\nfi\n\nif [ ! -d $2 ]; then\n    echo \"$2 is not a directory!\" 1&gt;&amp;2\n    exit 1\nfi\n\n# Process each file in directory_1, comparing it to directory_2\nmissing=0\nfor filename in $1\/*; do\n    fn=$(basename \"$filename\")\n    if [ -f \"$filename\" ]; then\n        if [ ! -f \"$2\/$fn\" ]; then\n            echo \"$fn is missing from $2\"\n            missing=$((missing + 1))\n        fi\n    fi\ndone\necho \"$missing files missing\"<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nNow on to the real work. We are going to improve the&nbsp;home_space&nbsp;function in our script to output more information. You will recall that our previous version looked like this:<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">home_space()\n{\n    # Only the superuser can get this information\n\n    if [ \"$(id -u)\" = \"0\" ]; then\n    echo \"&lt;h2&gt;Home directory space by user&lt;\/h2&gt;\"\n    echo \"&lt;pre&gt;\"\n    echo \"Bytes Directory\"\n        du -s \/home\/* | sort -nr\n    echo \"&lt;\/pre&gt;\"\n    fi\n\n}   # end of home_space\n     \n<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nHere is the new version:<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">home_space()\n{\n    echo \"&lt;h2&gt;Home directory space by user&lt;\/h2&gt;\"\n    echo \"&lt;pre&gt;\"\n    format=\"%8s%10s%10s   %-sn\"\n    printf \"$format\" \"Dirs\" \"Files\" \"Blocks\" \"Directory\"\n    printf \"$format\" \"----\" \"-----\" \"------\" \"---------\"\n    if [ $(id -u) = \"0\" ]; then\n        dir_list=\"\/home\/*\"\n    else\n        dir_list=$HOME\n    fi\n    for home_dir in $dir_list; do\n        total_dirs=$(find $home_dir -type d | wc -l)\n        total_files=$(find $home_dir -type f | wc -l)\n        total_blocks=$(du -s $home_dir)\n        printf \"$format\" $total_dirs $total_files $total_blocks\n    done\n    echo \"&lt;\/pre&gt;\"\n\n}   # end of home_space<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nThis improved version introduces a new command&nbsp;<a href=\"http:\/\/linuxcommand.org\/lc3_man_pages\/printf1.html\" style=\"color: #002740;\">printf<\/a>, which is used to produce formatted output according to the contents of a&nbsp;<i>format string<\/i>.&nbsp;printfcomes from the C programming language and has been implemented in many other programming languages including C++, Perl, awk, java, PHP, and of course, bash. You can read more about&nbsp;printf&nbsp;format strings at:<\/div>\n<ul style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\n<li><a href=\"http:\/\/www.gnu.org\/software\/gawk\/manual\/html_node\/Control-Letters.html#Control-Letters\" style=\"color: #002740;\">GNU Awk User&#8217;s Guide &#8211; Control Letters<\/a><\/li>\n<li><a href=\"http:\/\/www.gnu.org\/software\/gawk\/manual\/html_node\/Format-Modifiers.html#Format-Modifiers\" style=\"color: #002740;\">GNU Awk User&#8217;s Guide &#8211; Format Modifiers<\/a><\/li>\n<\/ul>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nWe also introduce the&nbsp;<a href=\"http:\/\/linuxcommand.org\/man_pages\/find1.html\" style=\"color: #002740;\">find<\/a>&nbsp;command.&nbsp;find&nbsp;is used to search for files or directories that meet specific criteria. In the&nbsp;home_space&nbsp;function, we use&nbsp;find&nbsp;to list the directories and regular files in each home directory. Using the&nbsp;wc&nbsp;command, we count the number of files and directories found.<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nThe really interesting thing about&nbsp;home_space&nbsp;is how we deal with the problem of superuser access. You will notice that we test for the superuser with&nbsp;id&nbsp;and, according to the outcome of the test, we assign different strings to the variable&nbsp;dir_list, which becomes the list of words for the&nbsp;for&nbsp;loop that follows. This way, if an ordinary user runs the script, only his\/her home directory will be listed.<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nAnother function that can use a&nbsp;for&nbsp;loop is our unfinished&nbsp;system_info&nbsp;function. We can build it like this:<\/div>\n<div class=\"codeexample\" style=\"background-color: #e0e0e0; font-family: verdana, arial, helvetica, sans-serif; padding: 0.5em;\">\n<pre style=\"font-family: courier, lucidatypewriter, monospace;\">system_info()\n{\n    # Find any release files in \/etc\n\n    if ls \/etc\/*release 1&gt;\/dev\/null 2&gt;&amp;1; then\n        echo \"&lt;h2&gt;System release info&lt;\/h2&gt;\"\n        echo \"&lt;pre&gt;\"\n        for i in \/etc\/*release; do\n\n            # Since we can't be sure of the\n            # length of the file, only\n            # display the first line.\n\n            head -n 1 $i\n        done\n        uname -orp\n        echo \"&lt;\/pre&gt;\"\n    fi\n\n}   # end of system_info<\/pre>\n<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nIn this function, we first determine if there are any release files to process. The release files contain the name of the vendor and the version of the distribution. They are located in the&nbsp;\/etc&nbsp;directory. To detect them, we perform an&nbsp;ls&nbsp;command and throw away all of its output. We are only interested in the exit status. It will be true if any files are found.<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nNext, we output the HTML for this section of the page, since we now know that there are release files to process. To process the files, we start a&nbsp;for&nbsp;loop to act on each one. Inside the loop, we use the&nbsp;<a href=\"http:\/\/linuxcommand.org\/lc3_man_pages\/head1.html\" style=\"color: #002740;\">head<\/a>&nbsp;command to return the first line of each file.<\/div>\n<div style=\"background-color: white; font-family: verdana, arial, helvetica, sans-serif;\">\nFinally, we use the&nbsp;<a href=\"http:\/\/linuxcommand.org\/lc3_man_pages\/uname1.html\" style=\"color: #002740;\">uname<\/a>&nbsp;command with the &#8220;o&#8221;, &#8220;r&#8221;, and &#8220;p&#8221; options to obtain some additional information from the system.<\/div>\n<p><\/span><\/div>\n","protected":false},"excerpt":{"rendered":"<p>The Linux Command Line&nbsp;by William Shotts Now that  &#8230; <a title=\"The Linux Command Line&#8212;Flow Control &#8211; Part 3\" class=\"read-more\" href=\"https:\/\/yeslq.com\/?p=183\" aria-label=\"\u9605\u8bfb The Linux Command Line&#8212;Flow Control &#8211; Part 3\">\u9605\u8bfb\u66f4\u591a<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[51,52,53],"class_list":["post-183","post","type-post","status-publish","format-standard","hentry","category-uncategorized","tag-linux","tag-shell","tag-the-linux-command-line"],"_links":{"self":[{"href":"https:\/\/yeslq.com\/index.php?rest_route=\/wp\/v2\/posts\/183","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/yeslq.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/yeslq.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/yeslq.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/yeslq.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=183"}],"version-history":[{"count":1,"href":"https:\/\/yeslq.com\/index.php?rest_route=\/wp\/v2\/posts\/183\/revisions"}],"predecessor-version":[{"id":321,"href":"https:\/\/yeslq.com\/index.php?rest_route=\/wp\/v2\/posts\/183\/revisions\/321"}],"wp:attachment":[{"href":"https:\/\/yeslq.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=183"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/yeslq.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=183"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/yeslq.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=183"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}