Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a conditional assignment in bash?

Tags:

bash

I'm looking a way to build conditional assignments in bash:

In Java it looks like this:

int variable= (condition) ? 1 : 0; 
like image 878
Neuquino Avatar asked Mar 14 '10 02:03

Neuquino


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is if [- Z in bash?

In both cases, the -z flag is a parameter to the bash's "test" built-in (a built-in is a command that is built-into the shell, it is not an external command). The -z flag causes test to check whether a string is empty. Returns true if the string is empty, false if it contains something.

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.


2 Answers

If you want a way to define defaults in a shell script, use code like this:

: ${VAR:="default"} 

Yes, the line begins with ':'. I use this in shell scripts so I can override variables in ENV, or use the default.

This is related because this is my most common use case for that kind of logic. ;]

like image 56
Demosthenex Avatar answered Oct 13 '22 04:10

Demosthenex


As per Jonathan's comment:

variable=$(( 1 == 1 ? 1 : 0 ))   

EDIT:

I revised the original answer which just echo'd the value of the condition operator, it didn't actually show any assignment.

like image 38
Anthony Forloney Avatar answered Oct 13 '22 04:10

Anthony Forloney