0

Trying to learn about variable assignment and got a bit stuck

 #!/usr/bin/env bash
 
 ([ -f first.txt ] && [ -f second.txt ] && rm first.txt &&
    DELETE="File deleted") ||
    DELETE="File not found";
 echo "${DELETE}"

If first.txt is missing, I get the correct message of "File not found" however, if I then create another "first.txt" the rest of the script works in that it tests for it and deletes it, but the variable assignment does not appear to be working, or, it is being overwritten by the or command which should not be running if the file exist. Either way, I am not getting the "File deleted" message that I am expecting, simply a blank space. This works if I just echo the text, but I want to be able to assign it to a variable to be able to compile and send as an email alert. What is going on here?

2
  • Use an if clause/statement, if you're just beginning to write shell code. Commented Dec 1, 2022 at 12:38
  • The parentheses set up a subshell. When the subshell exits, the variable assignment within it is no longer valid. This might work if you replace the opening parenthesis with an opening curly brace ({) and the ending parenthesis with this sequence: semicolon, space, closing curly brace (; }). This provides grouping without creating a subshell. But it's much better to use an if/else clause because and/or chains have gotchas. Commented Dec 1, 2022 at 15:21

1 Answer 1

1

With an if clause/statement

#!/usr/bin/env bash

if [[ -f first.txt && -f second.txt ]]; then
  rm first.txt &&
  delete="File deleted"
else
  delete="File not found"
fi

printf '%s\n' "$delete"

Sign up to request clarification or add additional context in comments.

1 Comment

Right got you, I'm just learning about the Logical operators as a way to remove if statements, and here is an example of where this can't be done, as explained in the first example fo your wiki, thanks for that, that is gold dust by the way.

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.