Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a shell script if targeted file doesn't exist

Given the script below, I would like to avoid the execution of the pipeline if a file does not exist.

How may I exit the script straight away if the text file is not found?

ls */*.txt | grep ab1 | awk '{print $1, $1}' | sed "s/\"/\"\"/g" | xargs -L1 mv 
like image 512
amine Avatar asked May 30 '13 01:05

amine


People also ask

How do I exit shell script without exiting shell?

Use return . The return bash builtin will exit the sourced script without stopping the calling (parent/sourcing) script. Causes a function to stop executing and return the value specified by n to its caller.

How do you force exit a shell?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

How do you exit a script in shell script?

The exit statement is used to exit from the shell script with a status of N. Use the exit statement to indicate successful or unsuccessful shell script termination. The value of N can be used by other commands or shell scripts to take their own action.

How to exit if a file does not exist in Bash?

To exit if it doesn't, something like this would suffice: if [ [ ! -f x.txt ]] ; then echo 'File "x.txt" is not there, aborting.' exit fi The -f <file> is only one of the many conditional expressions you can use. If you look at the bash man-page under CONDITIONAL EXPRESSIONS, you'll see a whole host of them.

How to exit a PowerShell script from the console?

If you open the PowerShell console and type exit, it will immediately close. Using the Exit keyword in a script terminates only the script and not the console session from where we run the script. Save the script in the file as FuncTest.ps1 Write-Output "Inside function..." Function ExitFunctionTest { Write-Output "Inside function..." Exit }

How to check if a directory exists in shell script?

We can use " -d " attribute to check if a directory exists in shell programming. We can use -d attribute within single [..] or double brackets [ [..]] to check if directory exists. Similarly we use single brackets in this example to check if the directory is preset within shell script.

How to exit a script when command fails?

One approach would be to add set -e to the beginning of your script. That means (from help set): -e Exit immediately if a command exits with a non-zero status. So if any of your commands fail, the script will exit.


2 Answers

You can check for file existence with something like:

if [[ -f x.txt ]] ; then     echo file exists. fi 

To exit if it doesn't, something like this would suffice:

if [[ ! -f x.txt ]] ; then     echo 'File "x.txt" is not there, aborting.'     exit fi 

The -f <file> is only one of the many conditional expressions you can use. If you look at the bash man-page under CONDITIONAL EXPRESSIONS, you'll see a whole host of them.


If (as stated in a question update) you wish to check if a wildcard results in files, you can simply expand it, throwing away the errors. If there are none, you'll end up with an empty string which can be detected with -z:

if [[ -z "$(ls -1 */*.txt 2>/dev/null | grep ab1)" ]] ; then     echo 'There are no "*/*.txt" files.'     exit fi 

Note that I've used -1 to force one file per line even though Linux ls does that by default if the output device is not a terminal (from memory). That's just in case you try this on a machine that doesn't force one per line in that case.


Keep in mind however that, if you have spaces in your filenames, using ls and then awk to extract column 1 is not going to work too well. For example, the file abc ab1.txt will result in the extraction of only the abc bit.

Using find with -print0, combined with xargs with -0 is the usual way to properly process files which may have "special" characters in them. There are many other options you can give to find to ensure only the files required are processed, such as -maxdepth to limit how far down the directory tree you go, and -name to properly filter file names.

However, if you know that you will never have these types of files, it's probably okay to use the ls solution, just make sure you're comfortable with its shortcomings.

like image 51
paxdiablo Avatar answered Oct 11 '22 11:10

paxdiablo


Use test

A quick and short way of testing for existence:

test -e $FILENAME || exit 

You can chain it by doing:

test -e $FILENAME && something | something-else  

In which case something and something-else will only execute if the file exists.

For example:

➤ test -e ~/.bashrc && echo True || echo False True ➤ test -e ./exists-not && echo True || echo False False 

Aside: Note that [ is an alias for test. The semantics of [[ are defined by bash and can be found on the bash manpage

However...

...you are probably better off using find to get your files:

find ./ -maxdepth 2 -name "*ab1*.txt" -exec do-something-to-filename '{}' \; 

As the output of ls can not be reliably parsed. This will also only execute the command do-something-to-filename if the filename exist, which is what I think you are trying to do.

{} will be replaced by the filename for each invocation of do-something-to-filename.

like image 34
brice Avatar answered Oct 11 '22 12:10

brice