I have a Bash variable, $word
, which is sometimes a word or sentence, e.g.:
word="tiger"
Or:
word="This is a sentence."
How can I make a new Bash variable which is equal to only the first letter found in the variable? E.g., the above would be:
echo $firstletter t
Or:
echo $firstletter T
To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
In case your string contains newlines | head -n1 will select the first line first before the important commands select the first word from the string passed to it. The would return the first word of every line, not the first word.
word="tiger" firstletter=${word:0:1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With