简体   繁体   中英

Need to verify every file passed as an argument on the command line exists using a shell script

I am looking to create a shell script that reads command line arguments, then concatenates the contents of those files and print it to stdout. I need to verify the files passed to the command line exist.

I have written some code so far, but the script only works if only one command line argument is passed. If passing more than one argument, the error checking I have tried does not work.

#!/bin/bash

if [ $# -eq 0 ]; then
echo -e "Usage: concat FILE ... \nDescription: Concatenates FILE(s) 
to standard output separating them with divider -----."
exit 1
fi

for var in "$@"
do
    if [[ ! -e $@ ]]; then
            echo "One or more files does not exist"
            exit 1
    fi
done


for var in "$@"
do
    if [ -f $var ]; then
            cat $var
            echo "-----"
            exit 0
    fi
done

I need to fix the error checking on this so that every command line argument is checked to be an existing file. If a file does not exist, the error must be printed to stderr and nothing should be printed to stdout.

You have a bug in line 11:

if [[ ! -e $@ ]]; then

You do need to check for a given file here using $var like that:

if [[ ! -e "$var" ]]; then

And you exit prematurely in line 23 - you will always print only a single file. And remember to always quote your variable because otherwise your script would not run correctly on files that have a whitespaces in the name, for example:

$ echo a line > 'a b'
$ cat 'a b'
a line
$ ./concat.sh 'a b'
cat: a: No such file or directory
cat: b: No such file or directory
-----.

You said:

if a file does not exist, the error must be printed to stderr and nothing should be printed to stdout.

You aren't printing anything to stderr at the moment, if you want to you should do:

echo ... >&2

And you should use printf instead of echo as it's more portable even though you're using Bash .

All in all, your script could look like this:

#!/bin/bash

if [ $# -eq 0 ]; then
    printf "Usage: concat FILE ... \nDescription: Concatenates FILE(s) to standard output separating them with divider -----.\n" >&2
    exit 1
fi

for var in "$@"
do
    if [[ ! -e "$var" ]]; then
            printf "One or more files does not exist\n" >&2
            exit 1
    fi
done

for var in "$@"
do
    if [ -f "$var" ]; then
            cat "$var"
            printf -- "-----\n"
    fi
done

exit 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM