The title remains

Please tell me how to check the type of the value in the variable.
Is there anything that returns int for int type and string for string?
Even if you look for it, it is difficult to find it.
Thank you.

  • Answer # 1

    Anything that has been extended with Bash, etc.,nois the data type for shell scripts considered within the scope of#!/bin/sh. Everything is a string.

    expris in command format, but what you receive is anumber string, not the number itself.

    Check whether the given data is a numerical value with a regular expression, or check if it can be calculated by throwing toexprorbc, etc. There is a way.

  • Answer # 2

    If you want to check integers, strings, and arrays using thedeclareandtypesetcommands in Bash, use-poption of the>declarecommand.

    # Declaring variable i as an integer
    declare -i i = 1
    # increment i and display
    i = i + 1
    echo $i # =>2
    # check how it was declared with declare -p
    declare -p i
    # declare -i i
    # Is displayed, so use this

    In zsh, you can check the variable type as${(t) foo}.

    declare -i i = 1
    echo ${(t) i}
    # integer
    # Is displayed
    s = hoge
    echo ${(t) s}
    # scalar
    # Is displayed

    If you want to be POSIX compliant, there's no type of variable in the first place. If you want to check if the contents of a variable are something like an integer, usegrepetc.

    i = 0
    if echo "$i" | head -n1 | grep '^ [0-9] \ + $'>/dev/null;then
      echo "integer"
      echo "not integer"
    I think

    is good.

  • Answer # 3

    See theman bashtypesetdeclaresection of the built-in command for the attributes of the variable.

    Do you want to judge whether it's a string consisting only of numbers or a string that contains other than numbers?

    if test -n "$A" -a -z "${A // [0-9] /}"
    then echo only numbers
    else echo Non-numeric or empty

    (If you delete all the numbers and are empty, say that the original string was only numbers.)