Score:0

Bash test command to check files exists not works as expected

in flag

I have a simple bash script. I need to check if file exists and then do some actions related to check result. Script looks like:

#!/bin/bash

productionPackageJsonPath=/var/www/portaldev/current/package.jsonxxx
productionNodeModulesPath=/var/www/portaldev/current/node_modules

hasPackageJsonFile=$(test -f productionPackageJsonPath)
hasDiff=""

if [ "$hasPackageJsonFile" == "true"  ]
then
    echo "aaaaaaaaaaaaaaaaaaaa"
    hasDiff=$(diff ${productionPackageJsonPath} package.json)
else
    echo "bbbbbbbbbbbbbbbbbbb"
fi

This should return false cause package.jsonxxx does not exist. But I am getting always true or i dont know what. But console always write echo "aaaaaaaaaaaaaaaaaaa"

Can somebody tell me please what am I doing wrong? Thnxsm.

cn flag
where is the `-f`?
in flag
$(test -f productionPackageJsonPath)
Score:1
in flag

So my solution is:

productionPackageJsonPath=/var/www/portaldev/current/package.json

if [ -f $productionPackageJsonPath ]
then
    echo "aaaaaaaaaaaaaaaaaaaa"
    hasDiff=$(diff ${productionPackageJsonPath} package.json)
else
    echo "bbbbbbbbbbbbbbbbbbb"
    hasDiff=""
fi
Score:1
za flag
hasPackageJsonFile=$(test -f productionPackageJsonPath)

Now the output of the command test -f productionPackageJsonPath is assigned to hasPackageJsonFile. This variable will always be empty, since $(...) captures the output of programs, not results.

in flag
Thanks, but how to assign a result to the variable? Obviously I need result in variable.
za flag
`lastresult=$?` stores the error of the last command (0 := no error, success) in a variable, but you might as well (most of the time) use an if around the test directly, instead of an intermediate variable.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.