Length is the long dimension of any object. The length of a thing is the distance between its ends, its linear extent as measured from end to end. This shell script will find out given string length as command line argument.
#!/bin/bash # Write a shell script to echo the length of the given string as argument. string="$1" if [ $# -eq 0 ] then echo "Syntax: $(basename $0) string" exit 1 fi # get length of the string length=$(echo ${#string}) echo "String length = $length"
Following script optimized for speed, as suggested by Chris (see below in comments section)
#!/bin/bash # Write a shell script to echo the length of the given string as argument. # Version 2, as suggested by Chris F.A. Johnson string="$@" if [ $# -eq 0 ] then echo "Syntax: ${0##*/} string" exit 1 fi # get length of the string length=${#string} echo "String length = $length"
- RSS feed or Weekly email newsletter
- 5 comments... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
bullygram, your script is functionally equivalent to:
clear
read -ep $’enter the string\n’ str
printf “length\n%d\n” ${#str}
we can also do like this!
program:
#!/bin/bash
#include
clear
echo “enter the string”
read str
for i in “$str”;do
echo “length”
echo ${#i}
done
Thanks for sharing tips.
echo “Syntax: $(basename $0) string”
Why use an external command? The shell can do it internally:
echo “Syntax: ${0##*/} string”
length=$(echo ${#string})
What’s the point of using echo and command substitution (which is slow)?
length=${#string}
Hi Chris,
When I embed this “length=${#string}” in bash shell script it was throwing an error as shown below
“test.sh: bad substitution”
I guess, shell interpretted string after “#” character as comment.
Please help me out escape the # character and get required result.
Regards,
Suresh