Aš'aš naudoju šį scenarijų, kad pamatytumėte, ar failas egzistuoja:
#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File $FILE exists."
else
echo "File $FILE does not exist."
fi
Kokią sintaksę reikia naudoti, jei noriu tik patikrinti, ar failas neegzistuoja?
#!/bin/bash
FILE=$1
if [ $FILE does not exist ]; then
echo "File $FILE does not exist."
fi
Komanda test ([
čia) turi loginį operatorių "not", kuris yra šauktukas (panašiai kaip ir daugelyje kitų kalbų). Pabandykite tai padaryti:
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
Galite paneigti išraišką naudodami "!":
#!/bin/bash
FILE=$1
if [ ! -f "$FILE" ]
then
echo "File $FILE does not exist"
fi
Atitinkamas žinyno puslapis yra man test
arba lygiavertis man [
-- arba help test
arba help [
, jei tai yra integruota bash komanda.
[[ -f $FILE ]] || printf '%s does not exist!\n' "$FILE"
Be to, gali būti, kad failas yra sugadinta simbolinė nuoroda arba nereguliarus failas, pvz., lizdas, įrenginys arba fifo. Pavyzdžiui, norėdami pridėti sugadintų simbolinių nuorodų patikrinimą:
if [[ ! -f $FILE ]]; then
if [[ -L $FILE ]]; then
printf '%s is a broken symlink!\n' "$FILE"
else
printf '%s does not exist!\n' "$FILE"
fi
fi