Reading a variable line by line with while loop
James Michael Fultz
croooow at gmail.com
Wed Dec 2 01:13:44 UTC 2009
* Ray Parrish <crp at cmc.net> [2009-12-01 15:29 -0800]:
> Well, I'm making some progress. I have the following code which works to
> a point.
>
> while read ThisCommand; do
> ThisCommand=${ThisCommand// /__};
> if `echo "${History}" | grep "${ThisCommand}" 1>/dev/null 2>&1`
> then
> echo "nothing" >/dev/null
The colon (:) builtin which evaluates as a successful command execution
is useful where you to effectively do nothing in your script.
: does nothing
You could also perform a negative test in order to avoid the do-nothing
block of your if-statement. Also, you can evaluate grep's exit status
directly rather than the output of the command. You also probably want
to test for fixed strings rather than regexes, thus the '-F' option to
grep.
if ! echo "$History" | grep -F "$ThisCommand" >/dev/null
> else
> History="$History $ThisCommand";
> fi
> done < <(cat ~/.bash_history)
Here, you don't need cat (nor process substitution) at all and could
write it more efficiently.
done < ~/.bash_history
Also, if you're using Bash and want to read the contents of a file into
a variable, you can spare using cat as well.
FOO=`cat foobar.txt`
or
FOO=$(cat foobar.txt)
becomes
FOO=$(< foobar.txt)
> Command=`Xdialog --stdout --title "Ray's Bash Manager - Select
> Command to Copy" --cancel-label "Exit" --combobox "Select a Command to
> Copy to the Clipboard." 0 60 $History`
>
> The if statement is meant to catch duplicate lines, and it does, unless
> they contain quotes in them, and then they get duplicated in the output.
> Is there some way to trap even the lines with quotes in them?
Appears the conditional in your if-statement was faulty. if itself acts
only upon the exit status of the command list given to it -- not the
output of those commands.
if [ "$FOO" = "xyz" ]
It's actually the [ command performing the expression evaluation.
if [[ "$FOO" == "xyz" ]]
Again, the [[ command evaluates the expression.
if echo "$FOO" | grep xyz
Here, a pipeline using grep is used to test for the presence of
a string.
More information about the ubuntu-users
mailing list