How to retrieve the first 10 characters of a variable with Bash?
FOO="qwertzuiopasdfghjklyxcvbnm"
I need to get qwertzuiop
.
Using the head Command The head command is used to display the first lines of a file. By default, the head command will print only the first 10 lines.
To access the first n characters 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. length: The number of characters we need to extract from a string.
$# is typically used in bash scripts to ensure a parameter is passed. Generally, you check for a parameter at the beginning of your script. To summarize $# reports the number of parameters passed to a script. In your case, you passed no parameters and the reported result is 0 .
Dollar sign $ (Variable) The dollar sign before the thing in parenthesis usually refers to a variable. This means that this command is either passing an argument to that variable from a bash script or is getting the value of that variable for something.
If the variable is: FOO="qwertzuiopasdfghjklyxcvbnm"
then
echo ${FOO:0:10}
will give the first 10 characters.
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