1

I have a file name like

/etc/auto.abc on server 1
/etc/auto.def on server 2
/etc/auto.ghi on server 1

I am writing a single script for all servers and in that I want to cat the file.

Example: cat /etc/auto.abc or /etc/auto.def or /etc/auto.ghi. It should able to take the file which is present.

Thanks,

3 Answers 3

2

Something like this:

if [[ $(find . -name "auto*" -type f -maxdepth 1 -printf '\n' | wc -l) -eq 1 ]]
then
   cat auto*
else
   echo there are more files that match 'auto*'
fi

-printf '\n' is there to handle filenames which contain newlines correctly (see this answer). In else you should handle the situation if there are more than 1 file which matches auto* pattern - it's your decision what to do here.

1
  • Existence test. I like it.
    – Elder Geek
    Dec 14, 2016 at 17:59
0

Why not use a script to check for the existence of the file prior to trying to run an operation on it?

#!/bin/bash
if test -f "/etc/auto.def"; then cat /etc/auto.def;
elif test -f "/etc/auto.ghi"; then cat /etc/auto.ghi;
elif test -f "/etc/auto.abc"; then cat /etc/auto.abc;fi

Sources:

http://www.shellhacks.com/en/HowTo-Check-If-a-File-Exists

http://www.thegeekstuff.com/2010/06/bash-if-statement-examples/

4
  • readarray -t array <<< "$(pdc status -a 2>&1 | cat /etc/auto.* | grep -v "autotab" | cut -f1)". I am using a cat command in above statement and if I use the loop it will be complicated
    – venella
    Dec 14, 2016 at 18:08
  • @venella Why use cat at all if you are using grep? See man grep
    – Elder Geek
    Dec 14, 2016 at 18:12
  • My requirement is I need the contents of the file by eliminating the lines having "autotab". Either one among the 3 files the server will be having.
    – venella
    Dec 14, 2016 at 18:16
  • in that case grep -v "autotab" /etc/auto should provide the same output as `cat /etc/auto.* | grep -v "autotab" Some kind soul once referred me to the UUOC award for one of my answers. I've been stuck on studying man pages ever since and cat has been relegated to it's intended use to concatenate files.. ;-)
    – Elder Geek
    Dec 14, 2016 at 20:57
0

Have you considered using file globs?

The most permissive way would be:

cat /etc/auto*

But better in your case would be:

cat /etc/auto.???

Of course if there could be other unwanted files matching that glob, or if there could be more than one of the three files present (and you only want one), this doesn't take into account all those possibilities. But it's certainly the simplest way.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .