12

below is the code I executed in terminal

[root@idm ~]# x="$(date +%d%m%y)"    
[root@idm ~]# echo $x
270217
[root@idm ~]# echo ${#x}
6

Can someone help me understand why the output is 6? What is # essentially doing to the variable?

28

It's a parameter expansion that returns the length of the parameter, or the number of elements in an array, or the number of positional parameters.

Please read your shell's manual. The following is from the bash manual:

${#parameter}

The length in characters of the value of parameter is substituted. If parameter is * or @, the value substituted is the number of positional parameters. If parameter is an array name subscripted by * or @, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element.


And also, please don't make a habit of working in an interactive root shell. It's dangerous and reckless at best. Use sudo sparingly and only in situations that requires elevated privileges. Playing around with bash is something you definitely can do as an ordinary non-root user.

In the last few years, I've only used an interactive root shell for manually adding a single user for myself. It's a 2-minute job and then I never need to see a # prompt ever again on that machine.

| improve this answer | |
14

The # operator returns the length of a variable. In your case the variable x length is six.

Please do have a look at Parameter Substitution for more information.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.