awk if file exists

in awk how would check if a file exists if its possible. I found a script that has code to do it, but when i try it myself, it fails.

#!/bin/bash

ls -lTtRrU | awk '
BEGIN {
	working_directory = ".";
}

{
	file_name = "";
	absolute_path = "";
		
	if ($0 ~ /^\.\/.*:$/ ) {
		working_directory = substr($0, 1, length($0) - 1);
		gsub(" ", "\\ ", working_directory);
	} else if ($0 ~ /.*[jpeg|jpg|png]$/) {
		count++;
		for (i = 10; i < NF; i++)
		{
			file_name = file_name $i "\\ ";
		}
		file_name = file_name $NF;
		absolute_path = working_directory "/" file_name;
#this always returns 0
		if ( system( "[ -f " absolute_path " ] " ) )
		{
			print absolute_path;
		}
	}
}

END {
}'

Does the file in absolute_path exist? If it does, then zero is the expected return code. Any non-zero indicates failure. So, the test, in my opinion should be written this way:

if( system( "[ -f " absolute_path " ] " )  == 0 )
{
   printf( "file exists\n" );
}

thanks. why is it that the return value is 0 on success instead of failure?

1 Like