I'm doing a script in which I need to test a string and based on its result I'll decide if I go further or not.
The command below works fine (if the string starts with "Clean" it will print 1, otherwise 0).
echo | awk ' {print index("'"${task}"'", "Clean")}'
What I'm trying to do is to use the AWK with IF in a BASH script. Based on this post I did the following:
idx=$(awk '{print index("'"${task}"'", "Clean")}')
echo $idx
if [ "$idx" == "0" ]; then
echo hello
fi
As I said, when I run the script it prints "0", but the second "echo" doesn't print anything, and of course the if doesn't works either.
Can anyone help me?
TIA,
Bob
Awk is the wrong solution here. How about:
There's also a sneaky substitution method:
But I find that to be far less readable.
Chris reckons case is tidier... let's try that out:
My aesthetic sense says "hell no with bells on", and fiddling with the formatting (
Clean*) echo hello;;
or similar) won't help much, IMAO. If you want a conditional, use anif
, I say.Womble's answer is probably what I would go for, but you can also use grep:
Drop the
i
switch to grep if you want it case sensitive (or if you do not want it case insensitive :-p ).In your first example, you use
echo
to provideawk
with a file (stdin
), but in your script, there is no file forawk
to process and it "hangs" waiting for input. You could useecho
in your variable assignment in the$()
, but I prefer to use/dev/null
for this purpose (i.e. when there's no actual file to process).In order to avoid awkward quoting, you can use variable passing with the
-v
option to provide Bash variables to anawk
script.You should find that this works:
You should probably use womble's suggestion, though, since it doesn't require spawning a separate process.