如何在 Bash 或 Unixshell 中检查字符串中的第一个字符?

我正在用 Unix 编写一个脚本,在这个脚本中,我必须检查字符串中的第一个字符是否是“/”,如果是,则检查 Branch。

例如,我有一个字符串:

/some/directory/file

我想让这个返回1,然后:

server@10.200.200.20:/some/directory/file

返回0。

143550 次浏览

There are 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
$ 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

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

case $str in
/*)
echo 1
;;
*)
echo 0
;;
esac

printf '%c "$s"

This was mentioned by brunoais in a comment, and it might be the best option since:

  • it is likely POSIX. TODO confirm. The following quote from https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html suggests this:

    It shall not be considered an error if an argument operand is not completely used for a b, c, or s conversion.

  • it can extract the character to a variable unlike using case directly

  • unlike cut -c1 printf is a Bash built-in so it could be a little bit faster

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

cut -c1

This is POSIX, and unlike case:

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 command, but less efficient alternative:

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

printf '%s' is to avoid problems with escape characters: Bash printf literal verbatim string, e.g.,

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

outputs \ as expected.

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

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

Code:

 place="Place"
fchar=${place:0:1}
echo $fchar

Output:

P