If you are a traditional programmer, using bash
for scripting may seem limiting sometimes, but for certain tasks, bash
can be very productive. It turns out, some of the limits of bash
are really limits of older shells and people code to that to be compatible. Still other perceived issues are because some of the advanced functions in bash
are arcane or confusing.
Strings are a good example. You don’t think of bash
as a string manipulation language, but it has many powerful ways to handle strings. In fact, it may have too many ways, since the functionality winds up in more than one place. Of course, you can also call out to programs, and sometimes it is just easier to make a call to an awk
or Python script to do the heavy lifting.
But let’s stick with bash
-isms for handling strings. Obviously, you can put a string in an environment variable and pull it back out. I am going to assume you know how string interpolation and quoting works. In other words, this should make sense:
echo "Your path is $PATH and the current directory is ${PWD}"
The Long and the Short
Suppose you want to know the length of a string. That’s a pretty basic string operation. In bash
, you can write ${#var}
to find the length of $var
:
#/bin/bash echo -n "Project Name? " read PNAME if (( ${#PNAME} > 16 )) then echo Error: Project name longer than 16 characters else echo ${PNAME} it is! fi