This is a hack I just discovered:
DEBUG=true
$DEBUG && echo "Hello"
And this just happens to work because true
is an actual command which returns 0, and the &&
operator is happy with that:
» true
» echo $?
0
Is there a non-hackish way of execute a piece of code if a variable is set, to whatever value, except the empty string? Something like this, but as a readable one-liner (like the one above):
myvar="ggg"
if [ "$myvar" != "" ] ; then echo "Hello" ; fi
Bash – Check if variable is set To check if a variable is set in Bash Scripting, use -v var or -z $ {var} as an expression with if command. This checking of whether a variable is already set or not, is helpful when you have multiple script files, and the functionality of a script file depends on the variables set in the previously run scripts, etc.
Environment Variables Editor Start CMD as an administrator: press Win keybutton to open the start menu, type in cmd to search for the command prompt and press Ctrl + Shift + Enter to launch it as administrator (or just Enter to launch it as a current users, but in this case you won’t be able to edit the system environment variables).
Right click on the empty space of your desktop and select New -> Shortcut from the context menu. Copy-paste the following command in the shortcut target box and click on Next: Set “Environment Variables” as the name of the shortcut and click on Finish.
Another trick to run any (trivial/non-trivial) command stored in abc variable is: and press UpArrow or Ctrl-p to bring it in the command line. Unlike any other method this way you can edit it before execution if needed. This command will append the variable's content as a new entry to the Bash history and you can recall it by UpArrow.
If you want to use the value:
[[ -n $DEBUG ]] && echo "Hello"
If you want to use the negation of the value:
[[ -z $DEBUG ]] && echo "Hello"
That's I think is the shortest. Note the $
in front of the variable name is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With