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:
/some/directory/file
I want this to return 1, and:
server@10.200.200.20:/some/directory/file
to return 0.
cut -c1
This is POSIX, and unlike
case
actually extracts the first char if you need it for later:awk substr
is another POSIX but less efficient alternative:printf '%s'
is to avoid problems with escape characters: https://stackoverflow.com/a/40423558/895245 e.g.:outputs
\
as expected.${::}
does not seem to be POSIX.See also: How to extract the first two characters of a string in shell scripting?
Many ways to do this. You could use wildcards in double brackets:
You can use substring expansion:
Or a regex:
Consider the case statement as well which is compatible with most sh-based shells: