Bash, IF file exists then, 'spaces' trouble

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
Chiefahol

Bash, IF file exists then, 'spaces' trouble

Post by Chiefahol »

Hi

I'm looking for a way to check if a filename exists inside a bash file:

Code: Select all

filename= "some file.txt"
if [ -e $filename ]
then 
	somefunction
else 
	echo " "; echo "ERROR: File not found! Returning..."; sleep 2;
fi
This code works EXCEPT when the file name has a space in it. When the file name has a space I get:

Code: Select all

filetool.sh: 79: [: some: unexpected operator
How can i make this code also process file names that have spaces?

Any help appreciated. :mrgreen:
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
Chiefahol

Re: Bash, IF file exists then, 'spaces' trouble

Post by Chiefahol »

Probably also worth noting i'm using Mint 17.1 with the default bash compiler.
User avatar
Pilosopong Tasyo
Level 6
Level 6
Posts: 1432
Joined: Mon Jun 22, 2009 3:26 am
Location: Philippines

Re: Bash, IF file exists then, 'spaces' trouble

Post by Pilosopong Tasyo »

Moved to Scripts & Bash forum.

String variables need to be quoted as well, especially when spaces are involved:

Code: Select all

$filename
versus

Code: Select all

"$filename"
o Give a man a fish and he will eat for a day. Teach him how to fish and he will eat for a lifetime!
o If an issue has been fixed, please edit your first post and add the word [SOLVED].
Chiefahol

Re: Bash, IF file exists then, 'spaces' trouble

Post by Chiefahol »

thanks that worked :mrgreen:
Locked

Return to “Scripts & Bash”