How to check the first character in a string in Bash or UNIX shell?

前端 未结 4 412
无人共我
无人共我 2021-01-30 06:07

I\'m writing a script in UNIX where I have to check whether the first character in a string is \"/\" and if it is, branch.

For example I have a string:

/         


        
相关标签:
4条回答
  • 2021-01-30 06:43
    $ foo="/some/directory/file"
    $ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
    1
    $ foo="server@10.200.200.20:/some/directory/file"
    $ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
    0
    
    0 讨论(0)
  • 2021-01-30 06:55

    cut -c1

    This is POSIX, and unlike case actually extracts the first char if you need it for later:

    myvar=abc
    first_char="$(printf '%s' "$myvar" | cut -c1)"
    if [ "$first_char" = a ]; then
      echo 'starts with a'
    else
      echo 'does not start with a'
    fi
    

    awk substr is another POSIX but less efficient alternative:

    printf '%s' "$myvar" | awk '{print substr ($0, 0, 1)}'
    

    printf '%s' is to avoid problems with escape characters: https://stackoverflow.com/a/40423558/895245 e.g.:

    myvar='\n'
    printf '%s' "$myvar" | cut -c1
    

    outputs \ as expected.

    ${::} does not seem to be POSIX.

    See also: How to extract the first two characters of a string in shell scripting?

    0 讨论(0)
  • 2021-01-30 06:59

    Consider the case statement as well which is compatible with most sh-based shells:

    case $str in
    /*)
        echo 1
        ;;
    *)
        echo 0
        ;;
    esac
    
    0 讨论(0)
  • 2021-01-30 07:02

    Many ways to do this. You could use wildcards in double brackets:

    str="/some/directory/file"
    if [[ $str == /* ]]; then echo 1; else echo 0; fi
    

    You can use substring expansion:

    if [[ ${str:0:1} == "/" ]] ; then echo 1; else echo 0; fi
    

    Or a regex:

    if [[ $str =~ ^/ ]]; then echo 1; else echo 0; fi
    
    0 讨论(0)
提交回复
热议问题