check if a file exist with -f and convert the result into variable

trying to make the follwoing command to look for a full fine name work correctly but i can't for now.

The command i use to look for file "Lista*":


PathFileIN_Elab=/root/Testms/Files
ChkFileName="$(ls -1 -f $PathFileIN_Elab/"$line"* |xargs basename)"
[ -f "${ChkFileName}" ] && echo "File exist"; echo "Err: $?"; NomeFil="${ChkFileName}" || echo "File does not exist"; echo "Err: $?"
echo ValNomeFileFullExt: "${ChkFileName}"

Result when file "Lista*"exist:


Err: 1

Err: 0

ValNomeFileFullExt: Lista.txt


++ I do not see any of my echos for file exist or not but the return code "err" for both cases... why?

Result when file "Lista*" do not exist:


ls: impossibile accedere a /root/Testms/Files/Lista*: No such file or directory basename: missing operand

Usare `basename --help' per ulteriori informazioni.

Err: 1

Err: 0

ValNomeFileFullExt:


++ no echos for file exist or not + return code as before plus the basename message

What i'm trying to do is to have a good check of the file name (if exist with extension or not) and set it as a var that i will need after that check, and so:

a) So if the file exist i set the var with full name: NomeFil="${ChkFileName}"

b) if the file do not exist i would like to run a command (ny now in test it's just an echo).

Can somebody help me? i'm new on bash scripts.

Thanks in advance.

4

1 Answer

When using matching you can expect zero or more answers back, so it is good to use a for loop to test one object at a time or it will break your -f test statement.

#!/bin/bash
shopt -s nullglob
a="Lista*"
b="/root/Testms/Files/$a"
for c in $b; do [[ -f $c ]] && { d=1; break; }
done
[[ $d ]] && { echo File exists; \ echo ValNomeFileFullExt: $(basename "$c"); } || \ echo File does not exists

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like