Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number of tokens in bash variable

Tags:

bash

split

how can I know the number of tokens in a bash variable (whitespace-separated tokens) - or at least, wether it is one or there are more.

like image 457
flybywire Avatar asked Mar 12 '09 14:03

flybywire


People also ask

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do I count the number of elements in an array in bash?

Use "${#somearray[@]}" to get the number of elements in the array. Beware that first element of an array is ambiguous with ksh and bash as their arrays are space.

Is it true 1 or 0 bash?

There are no Booleans in Bash. However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs.

How do I count strings in bash?

'#' symbol can be used to count the length of the string without using any command. `expr` command can be used by two ways to count the length of a string. Without `expr`, `wc` and `awk` command can also be used to count the length of a string.


1 Answers

The $# expansion will tell you the number of elements in a variable / array. If you're working with a bash version greater than 2.05 or so you can:

VAR='some string with words' VAR=( $VAR ) echo ${#VAR[@]} 

This effectively splits the string into an array along whitespace (which is the default delimiter), and then counts the members of the array.

EDIT:

Of course, this recasts the variable as an array. If you don't want that, use a different variable name or recast the variable back into a string:

VAR="${VAR[*]}" 
like image 175
guns Avatar answered Sep 21 '22 21:09

guns