1

I have my Bash code like this:

copiedFlag=false
..
if [...]
cp originalFile newFile && copiedFlag=true
fi
..
if[....]
copiedFlag || ( cp originalFile newFile && copiedFlag=true )
fi
..

if [ copiedFlag == true ]; then
cp newFile originalFile
fi
..

The compound condition copiedFlag || ( cp originalFile newFile && copiedFlag=true ) somehow doesn't work.

But if I do this, it works: copiedFlag || cp originalFile newFile && copiedFlag=true

This is an important step in my logic, hence I want to ensure that my assignment is absolutely correct by enclosing it in braces. Why does this not work? What am I doing wrong?

2
  • I guess you missed a $: $copiedFlag || ( cp originalFile newFile && copiedFlag=true ) Commented Aug 23, 2017 at 11:06
  • You must dereference/expand copiedFlag everywhere outside assignments to it, thus also in if [ $copiedFlag == true ]; then ... Commented Aug 23, 2017 at 11:16

1 Answer 1

1

The compound condition copiedFlag || ( cp originalFile newFile && copiedFlag=true ) somehow doesn't work.

It doesn't work because you are forking a new subshell and changes made to copiedFlag are not visible in current shell.

You don't really need to spawn a subshell here, just use brace expression { ...; } as:

"$copiedFlag" || { cp originalFile newFile && copiedFlag=true; }
Sign up to request clarification or add additional context in comments.

2 Comments

The test must start with a $: $copiedFlag || { cp originalFile newFile && copiedFlag=true; }
Great Anubhava. I had put the $ alright, but I think the curly brace is the winner. ! will try it out and update shortly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.