Baptiste Pernet
Baptiste Pernet

Reputation: 3384

Test existence of files in shell

I have a list of files and I would like to pipe to a command to test if each files exists

cat files.txt | command

Does it exist any command to do that ? Do I have to write a script ? Can you help me to write it ?

For example:

> cat files.txt
libs/cakephp/app_exp/views/elements/export-menu.ctp
libs/cron/prad_import.php
main/css/admin/remarketing-graph.css
main/images/dropd-arrow.png
main/includes/forms/export/export_menu.php
main/jquery/jquery/jquery.cookie.js
main/mvc/controllers/remarketing/prad_controller.php
main/mvc/controllers/remarketing/remarketing_controller.php

but some of this files doesn't exits, so I want to do

> cat files.txt | command
libs/cakephp/app_exp/views/elements/export-menu.ctp
main/css/admin/remarketing-graph.css
main/images/dropd-arrow.png
main/includes/forms/export/export_menu.php
main/jquery/jquery/jquery.cookie.js

that returns only the existing files

Upvotes: 1

Views: 125

Answers (2)

shellter
shellter

Reputation: 37258

Are you really using #!/bin/sh? In what context? An old Unix env, or in modern, stripped-down env with minimal cmds?

Can you use #!/bin/bash or #!/bin/ksh? That will make it easier.

But in any shell this should work

while read line ; do if [ -f "$line" ] ; then echo "$line" ; fi ; done < files.txt

This should allow for file/paths with spaces in them, but if other odd chars are embedded in the filenames then more work maybe required.

IHTH

Upvotes: 1

David C. Rankin
David C. Rankin

Reputation: 84521

test -f "files.txt" && cat "files.txt" | command

Also

[[ -f "files.txt" ]] && cat "files.txt" | command  # in BASH

take your pick. test is more portable.

Understanding that you want command to test for file existence, then you do not need a pipe at all. You can do something like this with a while loop:

while read file; do
    if test -f "$file"; then
        echo "the file exists"  # or whatever you want to do
    else
        echo "the file does NOT exist"  # or whatever you want to do
    fi
done < "files.txt"

This will read the file line-by-line and test each file for existence. You can also read all filenames from files.txt into an array and then loop through the array if you prefer. And yes, the above can be a script.

Upvotes: 1

Related Questions