shell

Check if parameters contains null


I would like to see if a input parameter to a shell script contains null.

I have the following script (test-print-null.sh):

#!/bin/sh                                                                                                                                                                                                                                                                             
printf "All params: $@\n"
printf "Value at pos 0: $0\n"
printf "Value at pos 1: $1\n"
printf "Value at pos 2: $2\n"
[[ -z "$1" ]] && printf "Pos 1 is null\n"
[[ -z "$2" ]] && printf "Pos 2 is null\n"

for var in "$@"
do
    ${var:+false} [ -n "${var+1}" ] && printf "Params is null!\n" && for param in "$@"; do printf "Params: %s \n" "$param" ; done;
done;

I then run the script ./test-print-null.sh "hello" "" which tells me that pos 2 is null. However, I would like to embed a null-char in the string hello and check for that. I tried ./test-print-null.sh "hel\0lo" "" which does not work as expected.


Solution

  • I would like to embed a null-char in the string hello

    It is impossible to embed a null characters in a string. Strings end with zero byte in shell.

    Variables can be unset or set. If set, variables can be empty or not empty. [[ -z checks if a string is empty (-z like "Zero").

    to a shell script contains null.

    It is not possible to check if a variable or an argument contains zero byte in shell.

    which tells me that pos 2 is null.

    The second positional argument is an empty string, yes.