새 정의가 비어 있지 않은 경우 변수를 재정의하세요.

새 정의가 비어 있지 않은 경우 변수를 재정의하세요.

나는 이것을 가지고있다:

master="master";
integration="integration";

if [ -f '.vcs.json' ]; then
    master=`read_json -f .vcs.json -k git.master`
    integration=`read_json -f .vcs.json -k git.integration`
fi

그러나 read_json의 결과가 비어 있지 않은 경우에만 기본/통합 변수를 재정의하고 싶습니다.

나는 다음과 같은 것을 생각하고 있습니다 :

master="master";
integration="integration";

if [ -f '.vcs.json' ]; then
    master="${`read_json -f .vcs.json -k git.master`:-master}"
    integration="${`read_json -f .vcs.json -k git.integration`:-integration}"
fi

하지만 구문이 올바른지 확실하지 않습니다.

답변1

문자열이 비어 있지 않을 때만 작업을 수행하려면 변수를 참조할 때 매개변수 기본값을 사용하세요.

master="$(read_json -f .vcs.json -k git.master)"

하위 쉘 명령이 출력을 반환하지 않으면 변수는 null이 됩니다. 그런 다음 기본 교체를 통해 이를 활용할 수 있습니다.

do-a-thing "${master-master}" # if 'master' is null, use the default value 'master'
                              # otherwise, use the contents of the variable

답변2

논리를 거꾸로 뒤집겠습니다.

# Note that the variables 'master' and 'integration' are NOT defined yet
if [ -f '.vcs.json' ]; then
  master="${`read_json -f .vcs.json -k git.master`:-master}"
  integration="${`read_json -f .vcs.json -k git.integration`:-integration}"
fi
# Set default values if empty or missing
: ${master:=master} ${integration:=integration}
# They are now guaranteed to be non-empty
echo $master $integration

관련 정보