Linux file exists error

3 ways to check if file exists in bash

In this blog post, we will discuss 3 different ways to check if a file exists in Bash. This is an important skill to have when you are working with files in a Linux environment. Each of these methods has its own benefits and drawbacks, so it is important to understand them all before deciding which one to use. Let’s get started!

The following Linux commands can be used to check if a file exists in bash.

  • test -f /path/to/file && echo “FILE exists.” || echo “File does not exist”
  • [ -e /path/to/file ] && echo “FILE exists.” || echo “File does not exist”
  • [ -f /path/to/file ] && echo “FILE exists.” || echo “File does not exist”

Check if a File Exists Using the test Command in bash

The first method we will discuss is using the test command. This is a built-in command in Bash that can be used to test various things. In this case, we are interested in using it to check if a file exists. The syntax for this command is as follows:

If the file exists, this command will return a 0 exit code. If the file does not exist, it will return a non-zero exit code. So, we can use this command to check if a file exists like so:

if test -e /path/to/file; then
echo “File exists”
else
echo “File does not exist”
fi

We can do this in one command like this.
test -e /path/to/file && echo “FILE exists.” || echo “File does not exist”

Check if a File Exists Using if statement -e option in bash

The best Linux command to check if a file Exists in bash is using the if statement -e option. The -e option is a built-in operator in Bash to check file exists. If the file exists, this command will return a 0 exit code. If the file does not exist, it will return a non-zero exit code.

The syntax for this operator is as follows:

if [ -e /path/to/file ] ; then
echo “File exists”
else
echo “File does not exist”
fi

We can do this in one command.

[ -e /path/to/file ] && echo “FILE exists.” || echo “File does not exist”

Check if a File Exists Using -f option in bash if statement

The third method we will discuss is using the -f option in if statement. The -e option checks if the file path exists, while the -f option checks if the file path exists and if it is a regular file. The syntax for these operators are as follows:

if [-f /path/to/file ] ; then
echo “File exists”
else
echo “File does not exist”
fi

we can do this in one command line.
[ -f /path/to/file ] && echo “FILE exists.” || echo “File does not exist”

File test operators in bash

The test command includes the following FILE operators that allow you to test for particular types of files:

  • -d FILE FILE exists and is a directory.
  • -e FILE FILE exists.
  • -r FILE FILE exists and the read permission is granted.
  • -s FILE FILE exists and it’s size is greater than zero (ie. it is not empty).
  • -w FILE FILE exists and the write permission is granted.
  • -x FILE FILE exists and the execute permission is granted.
Читайте также:  Acer aspire one and linux

As you can see, there are many different ways to check if a file exists in Bash. Each of these methods has its own benefits and drawbacks, so it is important to understand them all before deciding which one to use. In general, the “test” command is the simplest and most reliable way to check if a file exists. However, the other methods can be useful in certain situations. Thanks for reading!

David is a Cloud & DevOps Enthusiast. He has years of experience as a Linux engineer. He had working experience in AMD, EMC. He likes Linux, Python, bash, and more. He is a technical blogger and a Software Engineer. He enjoys sharing his learning and contributing to open-source.

howtouselinux.com is dedicated to providing comprehensive information on using Linux.

We hope you find our site helpful and informative.

Источник

Syntax error checking if file exists [closed]

Questions describing a problem that can’t be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers.

A bash script running in Amazon Linux 2 is trying to test if a file exists. Then if it does exist, the script should delete the file. The following error gets thrown every time the script runs. What needs to change in the script in order for the error to no longer be a problem?

File "/home/username/write_hosts.sh", line 3 if [ -f /home/username/hosts ] ^ SyntaxError: invalid syntax 
#!/usr/bin/env bash if [ -f /home/username/hosts ] then rm /home/username/hosts fi declare -a arr_of_tags=("this-master" "this-worker") for i in "$" do echo ["$i"] >> /home/username/hosts echo "About to test ip array for $i" declare -a arr_of_ips=$(aws ec2 describe-instances --region us-west-2 --query "Reservations[*].Instances[*].PrivateIpAddress" --filter "Name=tag:Name,Values=$i" --output=text) for j in "$" do echo "$j" >> /home/username/hosts done done 
[username@ip-10-0-0-73 ~]$ bash --version GNU bash, version 4.2.46(2)-release (x86_64-koji-linux-gnu) Copyright (C) 2011 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software; you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. You have new mail in /var/spool/mail/username 

Note: The contents of /var/spool/mail/username are not new. Just the same error shown at top above. Per @Jesse_b’s suggestion:

[username@ip-10-0-0-73 ~]$ echo $PATH /usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/username/.local/bin:/home/username/bin [username@ip-10-0-0-73 ~]$ sudo bash write_hosts.sh write_hosts.sh: line 2: $'\r': command not found write_hosts.sh: line 7: $'\r': command not found write_hosts.sh: line 9: $'\r': command not found write_hosts.sh: line 11: $'\r': command not found write_hosts.sh: line 13: syntax error near unexpected token `$'do\r'' 'rite_hosts.sh: line 13: `do 

Solution I changed the script to the following, then I ran dos2unix on the script before calling the script. The result is a working script now:

#!/usr/bin/env bash rm -f /home/username/hosts declare -a arr_of_tags=("this-master" "this-worker") for i in "$" do echo ["$i"] >> /home/username/hosts echo "About to test ip array for $i" declare -a arr_of_ips=$(aws ec2 describe-instances --region us-west-2 --query "Reservations[*].Instances[*].PrivateIpAddress" --filter "Name=tag:Name,Values=$i" --output=text) for j in "$" do echo "$j" >> /home/username/hosts done done 

Also, to confirm @steve’s suspicion, I see that python was being invoked in a cronjob definition, which I have corrected as follows:

echo '* * * * * lnxcfg bash /home/username/write_hosts.sh' | sudo tee /etc/cron.d/refresh_hosts 

Before the correction, python was being called in the preceding line and not bash . So I am marking @steve’s answer as accepted.

Читайте также:  Arch linux unofficial repositories

Источник

How to check if a file exists in a shell script

I’d like to write a shell script which checks if a certain file, archived_sensor_data.json , exists, and if so, deletes it. Following http://www.cyberciti.biz/tips/find-out-if-file-exists-with-conditional-expressions.html, I’ve tried the following:

[-e archived_sensor_data.json] && rm archived_sensor_data.json 

when I try to run the resulting test_controller script using the ./test_controller command. What is wrong with the code?

You must set one or more whitespace between opening square bracket «[» and option «-e» same as between filename and closing square bracket «]»

7 Answers 7

You’re missing a required space between the bracket and -e :

#!/bin/bash if [ -e x.txt ] then echo "ok" else echo "nok" fi 

I finally added two blank spaces, one after the opening square bracket and one before the closing one: [ -e archived_sensor_data.json ] && rm archived_sensor_data.json . The script seems to work now.

The main difference here is the fact that you are using «bash» scripting instead of «shell» scripting. Notice that the first line that you have added was #!/bin/bash, so you are telling the machine to use «bash» instead of sh. Because sh doesn’t recognize that argument «-e»

Here is an alternative method using ls :

(ls x.txt && echo yes) || echo no 

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null :

(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no 

This code means: «if ls is successful, there is such file, otherwise, there is none». If ls failed, it does not mean that file is missing. It might be some other error. For example, create file in directory owned by root and try to do ls under regular user. It will fail with Permission denied , which is not equivalent that file does not exist.

The backdrop to my solution recommendation is the story of a friend who, well into the second week of his first job, wiped half a build-server clean. So the basic task is to figure out if a file exists, and if so, let’s delete it. But there are a few treacherous rapids on this river:

  • Everything is a file.
  • Scripts have real power only if they solve general tasks
  • To be general, we use variables
  • We often use -f force in scripts to avoid manual intervention
  • And also love -r recursive to make sure we create, copy and destroy in a timely fashion.

Consider the following scenario:

We have the file we want to delete: filesexists.json

This filename is stored in a variable

:~/Documents/thisfolderexists filevariable="filesexists.json" 

We also hava a path variable to make things really flexible

:~/Documents/thisfolderexists pathtofile=".." :~/Documents/thisfolderexists ls $pathtofile filesexists.json history20170728 SE-Data-API.pem thisfolderexists 

So let’s see if -e does what it is supposed to. Does the files exist?

:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $? 0 

However, what would happen, if the file variable got accidentally be evaluated to nuffin’

:~/Documents/thisfolderexists filevariable="" :~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $? 0 

What? It is supposed to return with an error. And this is the beginning of the story how that entire folder got deleted by accident

Читайте также:  Linux bash бесконечный цикл

An alternative could be to test specifically for what we understand to be a ‘file’

:~/Documents/thisfolderexists filevariable="filesexists.json" :~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $? 0 
:~/Documents/thisfolderexists filevariable="" :~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $? 1 

So this is not a file and maybe, we do not want to delete that entire directory

man test has the following to say:

-b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file . -h FILE FILE exists and is a symbolic link (same as -L) 

Источник

No such file or directory? But the file exists!

I’ve downloaded a game (Shank) but the bin file doesn’t run. The error that is shown when I try to launch the executable is:

bash: ./shank-linux-120720110-1-bin: No such file or directory 

Thank you for your reply. I’ve done the command you said Agent86 but I have the same result. I’ve downloaded also the .deb file but there is a problem too. I don’t know what problem has this game.

Please confirm whether you’re running a 64-bit installation (that’s the most common case for this problem).

9 Answers 9

You’re probably trying to run a 32-bit binary on a 64-bit system that doesn’t have 32-bit support installed.

There are three cases where you can get the message “No such file or directory”:

  • The file doesn’t exist. I presume you’ve checked that the file does exist (perhaps because the shell completes it).
  • There is a file by that name, but it’s a dangling symbolic link.
  • The file exists, and you can even read it (for example, the command file shank-linux-120720110-1-bin displays something like “ELF 32-bit LSB executable …”), and yet when you try to execute it you’re told that the file doesn’t exist.

The error message in this last case is admittedly confusing. What it’s telling you is that a key component of the runtime environment necessary to run the program is missing. Unfortunately, the channel through which the error is reported only has room for the error code and not for this extra information that it’s really the runtime environment that’s to blame. If you want the technical version of this explanation, read Getting “Not found” message when running a 32-bit binary on a 64-bit system.

The file command will tell you just what this binary is. With a few exceptions, you can only run a binary for the processor architecture that your release of Ubuntu is for. The main exception is that you can run 32-bit (x86, a.k.a. IA32) binaries on 64-bit (amd64, a.k.a. x86_64) systems.

In Ubuntu up to 11.04, to run a 32-bit binary on a 64-bit installation, you need to install the ia32-libs package . You may need to install additional libraries (you’ll get an explicit error message if you do).

Since 11.10 (oneiric) introduced multiarch support, you can still install ia32-libs , but you can choose a finer-grained approach, it’s enough to get libc6-i386 (plus any other necessary library).

Источник

Оцените статью
Adblock
detector