Home > Enterprise >  Source bash from url only if file from the url exists and hide output
Source bash from url only if file from the url exists and hide output

Time:10-13

I've been searching the web but couldn't find the answer for my situation. I believe it's a first?

Anyway, here's what I'm trying to do;

#!/bin/bash

if source <(curl -s -f http://example.com/$1.txt); then
        echo "Found the file"
else
        echo "Couldn't find it"
fi

This is supposed to source the bash from http://example.com/$1.txt when I run the script like this; ./myscript.sh fileName while hiding any success of error outputs because I don't want them to show up.

However, while it works fine for the files that exist, it still says "Found the file" even if the file isn't there and sources the bash from an empty file because of the -f flag. If I remove the -f flag then it works and says "Couldn't find it" but it also returns an HTTP error since the file isn't there and as I said, I want to hide the errors too.

How can I work this around?

CodePudding user response:

The result code from source is simply the last command in the sourced file. If the file is empty (as it will be if curl fails) that's a success.

What you can do is guard against an error from curl separately.

if source <(curl -s -f "http://example.com/$1.txt" || echo "exit $?"); then
  • Related