Home > Mobile >  Bash Variable assignment issue
Bash Variable assignment issue

Time:12-01

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?

CodePudding user response:

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"

  • Related