0

I have written some code that uses the /bin/true by accident and I want to force the usage of the builtin of true and false.. any Idea what is the correct way of doing so?

#!/usr/bin/env bash
set -eEuo pipefail

CONFIRM=false
if [[ $1 == "Y" ]]; then
  CONFIRM=true
fi

"${CONFIRM}" || echo "Deletion will not happen, please run with '${0} Y' to confirm"

if $CONFIRM; then
 echo "I deleted the stuff!"
fi
  • 1
    This should use the built-in if it exists. That said, I don't think it matters. The only difference between the built-in and `/bin/true` would be whether a process is started, not in the exit status either produces. – chepner Oct 19 '21 at 14:21
  • 1
    you can shorten the code a bit: `[[ $1 == Y ]] && confirm=true || confirm=false` – glenn jackman Oct 19 '21 at 14:22
  • 1
    Get out of the habit of using ALLCAPS variable names, leave those as reserved by the shell. One day you'll write `PATH=something` and then [wonder why](https://stackoverflow.com/q/27555060/7552) your [script is broken](https://stackoverflow.com/q/28310594/7552). – glenn jackman Oct 19 '21 at 14:22
  • 1
    and @chepner is right: bash looks for builtins before external commands. At a prompt, enter `type -a true`, and see [3.7.2 Command Search and Execution](https://www.gnu.org/software/bash/manual/bash.html#Command-Search-and-Execution) in the manual – glenn jackman Oct 19 '21 at 14:24
  • @glenn-jackman the shorter code is more voodoo for some. The allcaps have been fixed in the original script – goergettica Oct 20 '21 at 23:32

1 Answers1

2

To me, this looks like a job for if ... else:

#!/usr/bin/env bash
set -eEuo pipefail

if [[ $# -eq 1 && $1 == Y ]]; then
  echo "I deleted the stuff!"
else
  echo "Deletion will not happen, please run with '${0} Y' to confirm"
fi

If you need to save the result:

#!/usr/bin/env bash
set -eEuo pipefail

# with the set-mode above, you can set `conform` like this:
[[ $# -eq 1 && $1 == Y ]] && confirm=$? || confirm=$?
# otherwise, you could just set it after the above test

# truth test
[[ $confirm -eq $() ]] || echo "Deletion will not happen, please run with '${0} Y' to confirm"

# truth test again
if [[ $confirm -eq $() ]]; then
    echo "I deleted the stuff!"
fi
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108