Loops and Functions
Goal
You will learn loops and functions in a form you can actually use. In particular, you will make them not break in boundary situations such as "when no files match", "when an argument contains a space", and "when there are no arguments at all", and at the end you fix, by cause, four scripts that are right by hand but wrong only in cron.
Why it matters
Shell functions do not return values. Values you compute go out through standard output, and success or failure is reported through the exit code. Only when you keep this convention does natural usage such as if is_number "$x" become possible. And do not parse ls for a file list; leave it to the shell's glob. $(ls *.log) breaks on file names that contain spaces, and when nothing matches it feeds an error message into the loop. Using a glob instead creates another trap, where the pattern string remains as it is when nothing matches, so you need a line of defense inside the loop.
Even when loops and functions are correct, the result changes depending on who calls the script and in what environment. cron runs jobs with /bin/sh, without the login shell's PATH, locale, and working directory. That is why reports of "it works when I run it" never stop, and some of them are only wrong numbers without a single line of error. The final incident has you go through four of those differences at once.
Steps
- Create
/root/bin/loop1.shso that it prints1through5, one per line. - Create the directory
/root/loops/logsand put 4.logfiles and 2.txtfiles in it. Then create/root/bin/count.sh <디렉터리>(the argument is a directory) so that it prints only the number of.logfiles directly under that directory. If given an empty directory, it must print 0. - Put at least 3 lines into
/root/loops/users.csvin the format이름,역할(name, role), and create/root/bin/readcsv.shso that it reads that file and prints one line at a time in the format이름(역할)(name followed by the role in parentheses). Run it without arguments. - In
/root/bin/lib.sh, define aslugifyfunction. It converts the words to lowercase and joins them with hyphens./root/bin/use.shmust use it by loading that file with source.use.sh Hello World->hello-world. - Create
/root/bin/isnum.sh <문자열>(the argument is a string). If it consists only of digits, the exit code is 0; otherwise it is a nonzero code. It must print nothing. An empty string, a sign, and a decimal point are all not numbers. - Create
/root/bin/each.shso that for each argument it receives, it prints one line in the format[인자](the argument in square brackets).each.sh "a b" cmust give two lines. If there are no arguments, it prints nothing. - Create
/root/bin/summary.sh <디렉터리>(the argument is a directory). It prints the number of.logfiles in that directory and the total number of lines as two lines,files=<개수>(the count) andtotal_lines=<합계>(the total). - Incident
incident sh-cron-only: four nightly aggregation jobs are right by hand but wrong or failing only under cron conditions. Tell apart the cause for each job, fix it so the same values come out under cron conditions too, and leave the cause code and evidence in the report.
Notes
- Incident tools:
incident listshows the incidents you can raise, each with a one-line symptom, andincident show <이름>(name) shows a ticket again. Raising the same incident again returns it to its original broken state. - The report is
/root/incident/<이름>/report.txt(name is the incident name). Write one line이름: <원인 코드>(target name: cause code) per target, and at the end addevidence: <원인을 보여 준 출력 한 줄>(one line of output that showed the cause, copied as is). The grader first looks at the actual behavior after your fix and uses the report to confirm your judgment. . /root/bin/lib.shandsource /root/bin/lib.share the same command. They do not create a new process, so the function definitions remain.wc -l < 파일(the Korean word means "file") does not attach the file name to the output, which makes it convenient for calculations.- This Pod has no cron daemon. The
cronrunthat the incident installs runs each crontab job once under the same conditions as cron (an empty environment, a minimal PATH,/bin/shfrom HOME). Those conditions are written in the header ofcronrun. - Common mistake 1: if you give an empty directory in steps 2 and 7, the glob is not expanded and the pattern string remains as it is, so the count comes out as 1.
- Common mistake 2: if you use
for x in $*in step 6,"a b"is split into two. - Common mistake 3: in the incident, running it by hand from a different working directory and concluding "it works". You only see the difference when you recreate exactly the place and environment cron starts from and compare.
Print 1 through 5
Create /root/bin/loop1.sh so that it prints 1 through 5, one per line.
You can use for x in 1 2 3 4 5 or the brace expansion {1..5}.
Count files with a glob
Create the directory /root/loops/logs and put 4 .log files and 2 .txt files in it. Then create /root/bin/count.sh <디렉터리> (the argument is a directory) so that it prints only the number of .log files directly under that directory. If given an empty directory, it must print 0.
If no files match, the shell leaves the pattern string as it is and the loop runs once. Put a line of defense inside the loop that checks whether the value is a real file, or use the shell option that turns no match into an empty list.
Read a CSV one line at a time
Put at least 3 lines into /root/loops/users.csv in the format 이름,역할 (name, role), and create /root/bin/readcsv.sh so that it reads that file and prints one line at a time in the format 이름(역할) (name followed by the role in parentheses). Run it without arguments.
read splits fields using IFS; there is a form that applies the separator only to that one read command. If you feed input through a pipe, the loop runs in a subshell and the variables do not survive, so feed the file in at the end of the loop.
Split a function out into a library
In /root/bin/lib.sh, define a slugify function. It converts the words to lowercase and joins them with hyphens. /root/bin/use.sh must use it by loading that file with source. use.sh Hello World -> hello-world.
Define the function in lib.sh and load it in use.sh with . or source. You must not copy and paste it.
Judge with an exit code
Create /root/bin/isnum.sh <문자열> (the argument is a string). If it consists only of digits, the exit code is 0; otherwise it is a nonzero code. It must print nothing. An empty string, a sign, and a decimal point are all not numbers.
If you print the result of the judgment, you cannot use it in an if statement. Report it only with return 0 / return 1.
Safely iterate over arguments that contain spaces
Create /root/bin/each.sh so that for each argument it receives, it prints one line in the format [인자] (the argument in square brackets). each.sh "a b" c must give two lines. If there are no arguments, it prints nothing.
Check the difference between for x in "$@" and for x in $*. When there are no arguments, it must do nothing.
Directory summary report
Create /root/bin/summary.sh <디렉터리> (the argument is a directory). It prints the number of .log files in that directory and the total number of lines in the following two lines.
files=<개수>(the count)total_lines=<합계>(the total)
Count the number of files and the total number of lines together. Even for an empty directory, 0/0 must come out.
Incident: right by hand, wrong only in cron
Running incident sh-cron-only raises the incident. The four nightly aggregation jobs in /srv/nightly/crontab (sales, stock, members, weekly) are right when you run them by hand from /srv/nightly, but wrong or failing under the same conditions as cron (cronrun /srv/nightly/crontab, results in /srv/nightly/out/<작업>.txt (job), log in /srv/nightly/cron.log). Find the cause for each job and fix it so that under cron conditions it gives the same values as when run by hand. You may fix the scripts or the crontab, but keep the four job lines of the crontab and do not touch /srv/nightly/data/. In /root/incident/sh-cron-only/report.txt, write four lines, sales: <코드>, stock: <코드>, members: <코드>, and weekly: <코드>, plus evidence: <관찰한 출력 한 줄> (one line of output you observed). Each job's code is one of the following: path (the PATH used to find commands), cwd (the starting directory), locale (LANG and LC_* are missing), shell (the shell that reads the script), home (HOME is different).
Direction: cron and a login shell differ in environment variables, starting directory, and the shell that reads the script. For each job, find which of these it depends on. Some jobs have no error in cron.log but only a wrong number. Tools: cron.log, env -i, type, locale, head -1. Concretely: the environment cron provides is written verbatim in the cronrun header. Recreate those conditions by hand with env -i, run the jobs one at a time, and look in the scripts for commands called without a path, paths that do not start with /, places that measure string length, and the first line. A NAME=값 (NAME=value) line in a crontab does not expand $변수 (a variable).