Linux if value null

how to check if $1 and $2 are null?

I am running some script which passing the string argument and I want to do if else statement shown as below:

if [ $1 != '' ] && [ $2 != '' ] then do something. 

If $1 didn’t exist then $2 would become $1 which makes the test of $1 and $2 both being null seem irrelevant.

@WinEunuuchs2Unix Not necessarily irrelevant — in some cases you want to ensure there’s actually something instead of blank or null string in arguments. $1 could be unset or set to null string by user of the script. Consider this sequence of command: $ set » bar then echo «x$<1>x»; Both variables are set, but one of them is null.

5 Answers 5

-z string True if the length of string is zero. 

When writing portable shell scripts, this flag should be used with care, since on certain commercial Unixes this flag is faulty. See my answer for linked sources.

Since this is tagged bash , I recommend that one use the extended test construct ( [[. ]] ), and forget the quotes:

Unless you are going for sh /POSIX compatibility, there is no reason not to use [[ ]] .

if [ "$1" == "" && "$2" == ""]; then echo NULL fi 

The && and other logical command separators are not allowed in the classic test . You have to use other test constructs instead (like -a , I think)

For the old version of the answer, see the second portion of this answer. If you want to know about details, read on

The cause of issue

In the question itself, it is reported that OP sees too many arguments error , which when tested in bash doesn’t seem to be the case:

$ [ $1 != '' ] && [ $2 != '' ] bash: [: !=: unary operator expected 

With /bin/sh which is actually symlinked to /bin/dash on Ubuntu, error reported as follows:

$ sh $ [ $1 != '' ] && [ $2 != '' ] sh: 1: [: !=: unexpected operator 

And the standalone /bin/test also :

$ /usr/bin/test $1 != '' /usr/bin/test: missing argument after ‘’ 

Sidenote: If you’re wondering what is /usr/bin/test and why I’m using bash and sh , then you should know that [ is alias for test command, which also exists as standalone executable or more commonly — as shell built-in which is what each shell will use first. As for if statements, they operate on exit statues of commands, hence why [ and test are commands, with everything else being arguments to that commands — improper order of those command-line args leads to errors.

Читайте также:  Linux find ssh key

Back to the topic: it’s unclear how OP got the unrelated error. However, in all 3 cases the issue is the same — unset variable will be treated as empty, thus what the shell sees with these unquoted variables is

which breaks syntax which test understands. Remember what I said about improper order of command-line arguments ? Hence why quoting is important. Let’s enable diagnostic output and see what shell executes:

$ set -x # throws error $ [ $1 != '' ] && [ $2 != '' ] + '[' '!=' '' ']' bash: [: !=: unary operator expected # no error $ [ "$1" != '' ] && [ "$2" != '' ] || echo null vars + '[' '' '!=' '' ']' + echo null vars null vars 

Better way to test unset variables

A very frequent approach that you see around is this:

 if [ "x$var1" == "x" ] && [ "x$var2" == "x" ]; then echo "both variables are null" fi 

In [ «x$1» = «x» ], the x prefix ensures that x»$1″ cannot possibly look like an operator, and so the only way the shell can parse this test is by treating = as a binary operator.

Presumably, this should be fairly portable since I’ve seen these in /bin/sh scripts. It also can be combined as in

Of course we could use -z flag, however according to research in some shells, particularly ksh88 (according to Stephane Chazelas), this flag is faulty.

See also

Источник

Bash If statement null

Looking for the correct syntax that looks at a bash variable and determines if its null, if it is then do . otherwise continue on. Perhaps something like if [ $lastUpdated = null?; then. else.

3 Answers 3

Just test if the variable is empty:

if [ -z "$lastUpdated" ]; then # not set fi 

There is a difference between a null-valued variable (assigned the empty string) and an unset variable; this answer does not make detect that distinction.

Prior to any assignment, a variable is unset. FOO= (no value give) is equivalent to FOO=»» , which sets the value of FOO to the empty string. The various parameter expansions ( $ vs $ , as an example) allow you to make this distinction. A quoted expansion of an unset variable, such as you use, expands to the empty string, so -z can not distinguish the two states.

@trojanfoe Just FYI. While the distinction exists, it’s not as common that one cares about the distinction 🙂

Expanding on @chepner’s comments, here’s how you could test for an unset (as opposed to set to a possibly empty value) variable:

The $ syntax gives an empty string if $variable is unset, and the string «word» if it’s set:

$ fullvar=somestring $ emptyvar= $ echo ">" $ echo ">" $ echo ">" <> 

@panepeter True, but my experience is that it’s easier and safer to just double-quote variable references than it is to figure out when it’s safe to leave them off. In this case, the fact that it requires a detailed explanation (including understanding what [ -z ] does and why) mans it’s much easier to use double-quotes. To put it another way: if someone thinks [ -z $ ] is a good way to test for a set variable, they’re likely to infer that [ -n $ ] is a good way to test for an unset variable, but it will completely fail.

Читайте также:  Linux kernel module name

To sum it all up: There is no real null value in bash. Chepner’s comment is on point:

The bash documentation uses null as a synonym for the empty string.

Therefore, checking for null would mean checking for an empty string:

if [ "$" = "" ]; then # $lastUpdated is an empty string fi 

If what you really want to do is check for an unset or empty (i.e. «», i.e. ‘null‘) variable, use trojanfoe’s approach:

if [ -z "$lastUpdated" ]; then # $lastUpdated could be "" or not set at all fi 

If you want to check weather the variable is unset, but are fine with empty strings, Gordon Davisson’s answer is the way to go:

if [ -z $ ]; then # $lastUpdated is not set fi 

Источник

Оболочка Bash: выясняем, имеет ли переменная значение NULL ИЛИ нет

Как проверить значение NULL в скриптах оболочки Linux или Unix?

Вы можете быстро проверить наличие нулевых или пустых переменных в скриптах оболочки Bash.

Вам необходимо передать параметр -z или -n в команду test или команду if или использовать условное выражение.

На этой странице показано, как узнать, имеет ли переменная оболочки bash значение NULL или нет с помощью команды test.

Чтобы узнать, является ли переменная bash нулевой:

Вернуть true, если переменная bash не установлена или имеет нулевую (пустую) строку:if [ -z “$var” ]; then echo “NULL”; else echo “Not NULL”; fi
Другой вариант, чтобы определить, установлена ли переменная bash в NULL:[ -z “$var” ] && echo “NULL”
Определите, является ли переменная bash NULL: [[ ! -z «$var» ]] && echo «Not NULL» || echo «NULL»

Давайте посмотрим синтаксиc команды test и примеры в деталях.

Синтаксис для команды if следующий:

my_var="nixCraft" if [ -z "$my_var" ] then echo "\$my_var is NULL" else echo "\$my_var is NOT NULL" fi
my_var="" if test -z "$my_var" then echo "\$my_var is NULL" else echo "\$my_var is NOT NULL" fi

Другой вариант, чтобы проверить, является ли переменная оболочки bash NULL или нет

[ -z "$my_var" ] && echo "NULL" [ -z "$my_var" ] && echo "NULL" || echo "Not NULL"
[[ -z "$my_var" ]] && echo "NULL" [[ -z "$my_var" ]] && echo "NULL" || echo "Not NULL"
## Check if $my_var is NULL using ! i.e. check if expr is false ## [ ! -z "$my_var" ] || echo "NULL" [ ! -z "$my_var" ] && echo "Not NULL" || echo "NULL" [[ ! -z "$my_var" ]] || echo "NULL" [[ ! -z "$my_var" ]] && echo "Not NULL" || echo "NULL"

Как найти значение NULL в оболочке, если есть условие в Unix

-N возвращает TRUE, если длина STRING отлична от нуля. Например:

#!/bin/bash var="$1" if [ ! -n "$var" ] then echo "$0 - Error \$var not set or NULL" else echo "\$var set and now starting $0 shell script. " fi

Пример: определить, является ли переменная bash NULL

Читайте также:  Key generation in linux

Следующий скрипт оболочки показывает различные возможности оболочки на основе bash/sh/posix:

#!/bin/bash # Purpose - Test for NULL/empty shell var # Author - Vivek Gite under GPL 2.0+ DEMO="cyberciti.biz" HINT="" ##################################### # Do three possibilities for $DEMO ## ##################################### for i in 1 2 3 do case $i in 1) DEMO="nixcraft.com"; HINT="value set";; 2) DEMO=""; HINT="value set to empty string";; 3) unset DEMO; HINT="\$DEMO unset";; esac ############################################### # Update user with actual values and action # $DEMO set to a non-empty string (1) # $DEMO set to the empty string (2) # $DEMO can be unset (3) ################################################ echo "*** Current value of \$DEMO is '$DEMO' ($HINT) ***" ######################################################################## ## Determine if a bash variable is NULL, set, unset or not set at ALL ## ######################################################################## if [ -z "$" ]; then echo "DEMO is unset or set to the empty string" fi if [ -z "$" ]; then echo "DEMO is unset" fi if [ -z "$" ]; then echo "DEMO is set to the empty string" fi if [ -n "$" ]; then echo "DEMO is set to a non-empty string" fi if [ -n "$" ]; then echo "DEMO is set, possibly to the empty string" fi if [ -n "$" ]; then echo "DEMO is either unset or set to a non-empty string" fi done

Источник

Shell script — exiting script if variable is null or empty

I am expecting to use the below variable in my bash script but in case if this is empty or null what would be the best way to handle it and exit from script.

I am seeing answers with ‘set -u’. I know this will work but is this good for production environment?

yes, variable consisting of whitespaces, considered empty. basically, I am thinking to put a check like if [[ ! -z «$» && «$» != ’’ ]] for this.

7 Answers 7

There is a built-in operator for requiring that a variable is set. This will cause the script to exit if it isn’t.

Commonly this is used with the : no-op near the beginning of the script.

The conflation of «unset or empty» is somewhat different. There is no similar construct for exiting on an empty but set value, but you can easily use the related syntax $ which expands to $var if it is set and nonempty, and default otherwise. There is also $ which only produces default if the variable is properly unset.

This can be particularly useful when you want to use set -u but need to cope with a possibly unset variable:

case $ in '') echo "$0: Need a value in var" >&2; exit 1;; esac 

I somewhat prefer case over if [ «$» = » ] , mainly because it saves me from having to wrap double quotes around $ , and the pesky case of a value in $var which gets interpreted as an option to [ and gives you an error message when you least expect it. (In Bash, [[ doesn’t have these problems; but I prefer to stick to POSIX shell when I can.)

Источник

Оцените статью
Adblock
detector