Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file exists and continue else exit in Bash

Tags:

I have a script that is one script in a chain of others that sends an email.

At the start of the script I want to check if a file exists and continue only if it exists, otherwise just quit.

Here is the start of my script:

if [ ! -f /scripts/alert ]; then     echo "File not found!" && exit 0 else         continue fi 

However I keep getting a message saying:

line 10: continue: only meaningful in a `for', `while', or `until' loop 

Any pointers?

like image 634
user1190083 Avatar asked Feb 05 '12 01:02

user1190083


People also ask

How do you check if a file already exists in bash?

-f filename ( test -f filename ) returns true if file exists and is a regular file.

How do I continue an if statement in bash?

Using Bash Continue with a for Loop Use the continue statement inside a conditional if to control the flow of a for : #!/bin/bash for i in {1.. 10} do if [[ $i == '9' ]] then echo "Number $i!" continue fi echo "$i" done echo "Done!"

How do you check if a file exists in a directory bash?

Check if Directory Exist The operators -d allows you to test whether a file is a directory or not. [ -d /etc/docker ] && echo "$FILE is a directory." You can also use the double brackets [[ instead of a single one [ .


1 Answers

Change it to this:

{ if [ ! -f /scripts/alert ]; then     echo "File not found!"     exit 0 fi } 

A conditional isn't a loop, and there's no place you need to jump to. Execution simply continues after the conditional anyway.

(I also removed the needless &&. Not that it should happen, but just in case the echo fails there's no reason not to exit.)

like image 148
Kerrek SB Avatar answered Sep 30 '22 16:09

Kerrek SB