Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short way to run command if variable is set

Tags:

bash

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
like image 592
blueFast Avatar asked Sep 21 '16 14:09

blueFast


People also ask

How do I check if a variable is set in Bash?

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.

How do I edit system variables in CMD?

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).

How to create environment variables shortcut in Windows 10?

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.

How to run a command from an ABC variable in Bash?

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.


1 Answers

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.

like image 93
Hasan Baidoun Avatar answered Oct 02 '22 06:10

Hasan Baidoun