Get first character of a string SHELL

I want to first the first character of a string, for example:

$>./first $foreignKey

And I want to get "$"

I googled it and I found some solutions but it concerns only bash and not Sh !

1

5 Answers

This should work on any Posix compatible shell (including sh). printf is not required to be a builtin but it often is, so this may save a fork or two:

first_letter=$(printf %.1s "$1")

Note: (Possibly I should have explained this six years ago when I wrote this brief answer.) It might be tempting to write %c instead of %.1s; that produces exactly the same result except in the case where the argument "$1" is empty. printf %c "" actually produces a NUL byte, which is not a valid character in a Posix shell; different shells might treat this case differently. Some will allow NULs as an extension; others, like bash, ignore the NUL but generate an error message to tell you it has happened. The precise semantics of %.1s is "at most 1 character at the start of the argument, which means that first_letter is guaranteed to be set to the empty string if the argument is the empty string, without raising any error indication.

3

Well, you'll probably need to escape that particular value to prevent it being interpreted as a shell variable but, if you don't have access to the nifty bash substring facility, you can still use something like:

name=paxdiablo
firstchar=`echo $name | cut -c1-1`

If you do have bash (it's available on most Linux distros and, even if your login shell is not bash, you should be able to run scripts with it), it's the much easier:

firstchar=${name:0:1}

For escaping the value so that it's not interpreted by the shell, you need to use:

./first \$foreignKey

and the following first script shows how to get it:

letter=`echo $1 | cut -c1-1`
echo ".$letter."
6

for shell sh

echo "hello" | cut -b 1 # -b 1 extract the 1st byte
h
echo "hello" |grep -o "." | head -n 1
h
echo "hello" | awk -F "" '{print $1}'
h

you can try this for bash:

s='hello'; echo ${s:0:1}
h
3

Maybe it is an old question. recently I got the same problem, according to POSIX shell manual about substring processing, this is my solution without involving any subshell/fork

a="some string here" printf 'first char is "%s"\n' "${a%"${a#?}"}"

2
printf -v first_character "%c" "${variable}"
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like