19
Fri, Apr
5 New Articles

The Linux Letter: I Once Was Lost but Now Am Found

Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Like humans, most computers tend to gain weight as they age. OK, they don't really gain weight. But they do tend to gather stuff on their hard drives that consumes expensive disk space--space that could be put to better use. Worse, that trash fills up your backup media, consuming time and materials there, too.

While many tomes have been written about disk space recovery on an iSeries, there is also an open-source tool available that can help you hunt down and manage files on your Integrated File System (IFS)--whether they are used as part of your OS/400 software, as part of PASE, or as part of a Linux partition.

Find or Find File

Most of you have used a Windows machine and are aware of the Windows "Find File" utility, a handy tool to find misplaced files over local or network drives. Thus, when you move to a UNIX-like OS, you may overlook one of the most powerful tools available, the Find utility, because you think it's just a command-line version of the utility with which you are so familiar. Bzzzzt! Wrong!

Even if you have been using Linux for some time, you still may not have an appreciation for the power and elegance embodied in the Find utility. A quick look at the feature list shows that Find can locate files 1) by name or partial name, 2) by size or a range of sizes, 3) by date and time of last access, last modification, or last change, 4) by comparison with the date/time of another file, 5) by owner, 6) by file permission, 7) by file type (directory, link, etc.), or 8) by any combination of the preceding. And once Find locates a file matching your criteria, it can execute a command against it, making the appropriate file name substitutions as required.

Here's the format of the Find command:

find path expression


Here, path is the directory from which Find begins it search, and expression is a group of operators passed to Find.

So that we can more easily discuss Find, I have created a bogus directory below, adding files and a directory to it. The files with the .java extension are, of course, Java programs. Files with .c or .cpp are C and C++ programs, respectively. And the lone file with the .sh extension is a shell script.

[klinebl@laptop2 demo]$ ll
total 12256
-rw-rw-r--    1 klinebl  klinebl      3148 Oct 28 11:28 Class5.java
drwxrwxr-x    2 klinebl  klinebl      4096 Oct 28 11:28 dir1
-rw-rw-r--    1 klinebl  klinebl      5120 Jan  1  2001 program1.java
-rw-rw-r--    1 klinebl  klinebl    102400 Feb  2  2002 program2.java
-rw-rw-r--    1 klinebl  klinebl   1024000 Mar  3  2003 program3.java
-rw-rw-r--    1 klinebl  klinebl  10240000 Apr  4  2003 program4.java
-rw-rw-r--    1 klinebl  klinebl      5120 Oct 28 11:10 program5.c
-rw-rw-r--    1 klinebl  klinebl    102400 Oct 28 11:10 program6.cpp
-rwxr-xr-x    1 klinebl  klinebl   1024000 Oct 28 11:10 program6.sh
[klinebl@laptop2 demo]$


Let's start with a very simple example in which we want to produce a listing of all Java programs. The command and the results are shown below:

[klinebl@laptop2 demo]$ find . -name "*.java" -print
./program1.java
./program2.java
./program3.java
./program4.java
./dir1/TeamStats.java
./Class5.java
[klinebl@laptop2 demo]$


The first parameter to the Find command is the path (or paths) to search. In this case, we're in the directory where we want to begin the search. Thus, we'll use a period (.) to denote the current directory. After the directory come the operators. The first (-name) specifies the file(s) that we want to find. The second operator causes the file name currently under consideration to be printed. Notice that there is a Java program in the dir1 directory that Find located. This is because Find will traverse your directory tree, starting at the point you indicated.

Let's try the same request, this time swapping the order of the operators:

[klinebl@laptop2 demo]$ find . -print -name "*.java"
.
./program1.java
./program2.java
./program3.java
./program4.java
./program5.c
./program6.cpp
./program6.sh
./dir1
./dir1/TeamStats.java
./Class5.java
[klinebl@laptop2 demo]$


Huh? What happened here? This anomaly deserves an explanation. The operators to Find return logical values and are divided into three categories:

  • Options, which affect how Find behaves and always return a true value
  • Tests, which can return true or false
  • Actions, the logical value of which depends on exit status of the action.


As it executes, Find traverses the directory (or directories) and for each file it finds, evaluates from left to right the expression (the list of operators) that you provide. It will continue the evaluation as long as it gets a true return value (indicating that the list of operators is logically ANDed together). Once a false value is returned, Find will cease evaluation and go on to the next file. In our successful example, the "-print" operator was executed only when the test "-name" returned a true value. Thus, only files matching our request were printed. If we put the "-print" operator before the test, it is always executed, producing the erroneous results.

Let's try a slightly more complicated example. This time, we want to find both Java and C++ programs. Here are the command and results:

[klinebl@laptop2 demo]$ find . ( -name "*.java" -o -name "*.cpp" ) -print
./program1.java
./program2.java
./program3.java
./program4.java
./program6.cpp
./dir1/TeamStats.java
./Class5.java
[klinebl@laptop2 demo]$


As with any logical expression, you can use parentheses to force the order of evaluation. In this case, we would need the parentheses so that "-print" will be executed whenever we find either a Java or C++ program.

You may be wondering what the backslashes are for. No, it wasn't transmission line noise injected when I sent this article to MC Press. Instead, the backslashes are used to let the shell know that you want the parentheses passed on to the command instead of being used by the shell itself. Failure to so mark the parentheses (called "escaping") results in the following error:

[klinebl@laptop2 demo]$ find . ( -name "*.java" -o -name "*.cpp" ) -print
bash: syntax error near unexpected token `('
[klinebl@laptop2 demo]$


Now that you have an idea how Find evaluates expressions, let's look at a series of simple examples that show it in use.

First, let's get a list of all files (-type f) that are greater than 512 K in size (-size +512k), followed by a list of files smaller than 512 K (-size -512k), followed by a list of files exactly 512 K. We'll use the "-ls" operator instead of the "-print" operator to indicate that we would like the output in the same format as given by the ls -dils command. The "-type f" is used to indicate only regular files, excluding things such as directories and symbolic links.

[klinebl@laptop2 demo]$ find . -type f -size +512k -ls
3335952 1004 -rw-rw-r--   1 klinebl  klinebl   1024000 Mar  3  2003 ./program3.java
3335953 10016 -rw-rw-r--   1 klinebl  klinebl  10240000 Apr  4  2003 ./program4.java
3335956 1004 -rwxr-xr-x   1 klinebl  klinebl   1024000 Oct 28 11:10 ./program6.sh
[klinebl@laptop2 demo]$ find . -type f -size -512k -ls
3335950    8 -rw-rw-r--   1 klinebl  klinebl      5120 Jan  1  2001 ./program1.java
3335951  104 -rw-rw-r--   1 klinebl  klinebl    102400 Feb  2  2002 ./program2.java
3335954    8 -rw-rw-r--   1 klinebl  klinebl      5120 Oct 28 11:10 ./program5.c
3335955  104 -rw-rw-r--   1 klinebl  klinebl    102400 Oct 28 11:10 ./program6.cpp
1341401    4 -rw-rw-r--   1 klinebl  klinebl      2910 Oct 28 11:28 ./dir1/TeamStats.java
3335957    4 -rw-rw-r--   1 klinebl  klinebl      3148 Oct 28 11:28 ./Class5.java
[klinebl@laptop2 demo]$ find . -type f -size 512k -ls
[klinebl@laptop2 demo]$


The difference between the comparisons was in the use (or lack thereof) of the plus sign (+) and the minus sign (-). The former means anything greater than, the latter means anything less than, and the absence of either means equal to.

What if we want a list of files that were modified over a year ago and are over 100 K in size?

[klinebl@laptop2 demo]$ find . -type f -mtime +365 -size 100k -ls
3335951  104 -rw-rw-r--   1 klinebl  klinebl    102400 Feb  2  2002 ./program2.java
[klinebl@laptop2 demo]$

 

The Find utility would be handy enough if all it did was produce listings (because you could use the output of Find as input to another command, as you'll see shortly). One of the operators available to Find is "-exec," which executes a command. Substituting "-print" for "-exec" in our first example yields the following:

[klinebl@laptop2 demo]$ find . -name "*.java" -exec echo {} ;
./program1.java
./program2.java
./program3.java
./program4.java
./dir1/TeamStats.java
./Class5.java
[klinebl@laptop2 demo]$

 

The "-exec" operator is one whose logical value is based upon the return value of the command(s) executed. If the command was successful, then "-exec" will be true and Find will continue to evaluate the expression. Otherwise, the evaluation will stop. Once again, the backslash character is used--this time to escape the semicolon. Find considers anything between "-exec" and a semicolon to be the command string to execute. You need to convince the shell to pass the semicolon to Find, hence the need to escape it.

Using Echo within "-exec" is rather boring. What if we wanted to do something more utilitarian? How about if we save disk space by using the gzip utility on every Java source file that hasn't been modified for over a year? (The gzip utility is a file compressor that, by default, compresses a file and renames it with an extension of "gz.")

 

[klinebl@laptop2 demo]$ find . -name "*.java" -mtime +365 -print -exec gzip {} ;
./program1.java
./program2.java
[klinebl@laptop2 demo]$ ll
total 12156
-rw-rw-r--    1 klinebl  klinebl      3148 Oct 28 11:28 Class5.java
drwxrwxr-x    2 klinebl  klinebl      4096 Oct 28 11:28 dir1
-rw-rw-r--    1 klinebl  klinebl        53 Jan  1  2001 program1.java.gz
-rw-rw-r--    1 klinebl  klinebl       147 Feb  2  2002 program2.java.gz
-rw-rw-r--    1 klinebl  klinebl   1024000 Mar  3  2003 program3.java
-rw-rw-r--    1 klinebl  klinebl  10240000 Apr  4  2003 program4.java
-rw-rw-r--    1 klinebl  klinebl      5120 Oct 28 11:10 program5.c
-rw-rw-r--    1 klinebl  klinebl    102400 Oct 28 11:10 program6.cpp
-rwxr-xr-x    1 klinebl  klinebl   1024000 Oct 28 11:10 program6.sh
[klinebl@laptop2 demo]$

 

Take special note of the fact that the "-exec" operator is called each time a matching file is found. Sometimes, you want to deal with the complete list of files as a group. To do that, pipe the output to the command you want to use to operate on the list. For example, the tape archiver (tar) program allows you to save a list of files in a single file called an archive. In the previous example, we simply "gzipped" each matching file. What if we wanted to archive the files instead? That's simple:

[klinebl@laptop2 demo]$ find . -name "*.java" -mtime +365 | xargs tar -czf myarchive.tgz
[klinebl@laptop2 demo]$ tar -tzf myarchive.tgz
./program1.java
./program2.java
[klinebl@laptop2 demo]$

 

The xargs utility builds and executes command lines from standard input. So the output of the Find command is reformed into this command:

tar -czf myarchive.tgz ./program1.java ./program2.java

 

Most of the time, you'll be better off using this form for efficiency's sake. Instead of spawning a process for each matching file, you'll only spawn one additional process for the list. Use "-exec" if you are interested in the outcome of the command you execute to effect the operation of Find or if the list you generate exceeds the maximum number of parameters that the command you wish to execute can handle.

Seek and Ye Shall Find

I've only touched on the simplest of uses for the Find utility. There are many operands available, but they vary by operating system. You'll need to check your documentation to determine what your vendor has added to the standard list. The GNU version included with RedHat 9 has 39 tests and a dozen supported actions. So the possibilities are endless.

The Find utility is supported both within the QSHELL and PASE environments on the iSeries, as well as on the various flavors of UNIX (and, of course, on Linux). So you can add it to your disk-cleaning arsenal on any of the platforms on which it is available.

Until next month, explore your IFS or Linux directories and see what you can find!


Barry L. Kline is a consultant and has been developing software on various DEC and IBM midrange platforms for over 20 years. Barry discovered Linux back in the days when it was necessary to download diskette images and source code from the Internet. Since then, he has installed Linux on hundreds of machines, where it functions as servers and workstations in iSeries and Windows networks. He recently co-authored the book Understanding Linux Web Hosting with Don Denoncourt. Barry can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..

Barry Kline 0

Barry L. Kline is a consultant and has been developing software on various DEC and IBM midrange platforms since the early 1980s. Barry discovered Linux back in the days when it was necessary to download diskette images and source code from the Internet. Since then, he has installed Linux on hundreds of machines, where it functions as servers and workstations in iSeries and Windows networks. He co-authored the book Understanding Web Hosting on Linux with Don Denoncourt. Barry can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: