Re: Substring search in dash [ _NOT_ bash ] shell
Hi,
if you cannot find a dash tutorial then get a tutorial for bash or sh and
test in dash whether the proposals apply properly.
(You can reach dash in dialog by typing "dash" into a bash window.)
Bash and dash both stem from S.R.Bourne's sh. The shell chapters of
his book "The Unix System" from 1983 still apply.
-------------------------------------------------------------------
As others already stated, the most easy way to look for a substring
is to use the "case" flow-control construct and its capability to
apply search patterns.
One should note the peculiarity of "case ... esac" when it shall be condensed
to a single line. In nearly all shell situations one replaces line break
by a ';' character.
The actually documented dash form
if [ "`hostname`" = bob ]
then echo bob.cfg
fi
may be written as
if [ "`hostname`" = bob ]; then echo bob.cfg; fi
But with "case" it is different. man dash descibes it by:
case word in
[(]pattern) list ;;
...
esac
Now if you do the condensation by the usual ';' characters
case "`hostname`" in ; bob) echo bob.cfg ;; ; esac
then you earn protest from both shells:
dash: 1: Syntax error: word unexpected (expecting ")")
bash: syntax error near unexpected token `;'
You rather have to use in both shells the form from man bash without
extra semicolons.
case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
I.e. for strings which contain "bob":
case "`hostname`" in *bob*) echo bob.cfg ;; esac
Note that a more modern form of `hostname` is $(hostname).
Both execute program hostname and the shell use their output text instead
the `` or $() constructs themselves.
-------------------------------------------------------------------
To get back to "if": It is less specialized.
Your initial line uses "[" which is an alias of command "test".
"test" returns 0 if it evaluates its arguments as "true", and 1 if "false".
(IT people had a strange humor back in the 80s.)
The "test" expression used is "A = B". There are operators like "-o" for
logical "or". "A -o B" is true if a is true, or if be is true, or both are
true.
For substring search you would have to employ a program like "grep".
It returns 0 if something was found, else it returns 1.
if hostname | grep 'bob' >/dev/null ; then echo bob.cfg ; fi
grep has a very powerful expression language which is not the same as
the shell patterns. It puts out to stderr what it finds. Here we dump
those messages to /dev/null.
Of course grep has its own fat man page.
-------------------------------------------------------------------
Have a nice day :)
Thomas
Reply to: