Script linux if null

Script linux if null

Find centralized, trusted content and collaborate around the technologies you use most.

Connect and share knowledge within a single location that is structured and easy to search.

I can’t wrap my head around this. Why would /dev/null be used as input to an if statement? What is the use of < /dev/null in the following?

if ( $PROG --version ) < /dev/null >/dev/null 2>&1; then $PROG else echo "failed" exit 1 fi 

I (think) I understand that > /dev/null 2>&1 is just used to suppress any output from both stdout and stderr .

2 Answers 2

If $PROG is a program that expects input from stdin , your script might stall forever waiting for you to type something in. The use of < /dev/null is to provide an empty input to such a program. You're right about the >and 2>&1 .

This snippet of script is checking to see if $PROG —version exits with a 0 status (success), and then runs that program without any flags. If $PROG —version fails, the script echoes «failed» and exits.

Thanks. I’m still not sure how useful this is if I know what $PROG is and I know that PROG —version isn’t waiting for input. For example, PROG=autoconf is one where I saw this. And I know that autoconf —version is not waiting for input. Is it still useful in this case?

@Carl Norum, could the if ( ‘$PROG —version’ ) (with angle brackets) be used here to execute the command and thus no need for < /dev/null ?

@fduff: (a) There are no angle brackets in your comment. (b) You have single quotes which will cause the shell to treat ‘$PROG —version’ as a string literal, not as a command to be executed, which will be an error unless you happen to have a command whose name is literally ‘$PROG —version’ . Can you clarify what you’re asking?

I meant that: » $PROG —version » to execute the command. The » » is used in SO for code` formatting.

I think you’re wondering why the redirection is outside the parentheses.

if ( $PROG --version ) < /dev/null >/dev/null 2>&1; then 

the parentheses aren’t part of the syntax of the if statement; they just specify command grouping. (It took me a moment to remember that myself; in csh/tcsh, parentheses are part of the syntax of an if statement.)

( echo one ; echo two ) | tr a-z A-Z 

In this case, since $PROG —version is a single command, the parentheses are unnecessary (unless $PROG expands to more than one command, but that’s unlikely).

So the redirection doesn’t apply to the if statement; it applies to $PROG —version . The purpose is to provide no input (as if reading from an empty file) to $PROG , and to discard anything it writes to stdout or stderr. If $PROG is a command that reads from stdin, even when invoked with —version , then without the input redirection it could hang waiting for keyboard input.

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

The script assumes that it’s safe to invoke $PROG (whatever it may be) only if $PROG —version doesn’t produce an error.

Note that you can apply redirection to an if statement:

if test_command ; then something else something_else fi < /dev/null >/dev/null 2>&1 

This redirects input and output for test_command , something , and something_else .

Источник

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.

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 

Источник

Читайте также:  Linux command copy folders

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

Источник

Оболочка 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»

Читайте также:  Bluetooth scanner kali linux

Давайте посмотрим синтакси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

Следующий скрипт оболочки показывает различные возможности оболочки на основе 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

Источник

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