[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] A string handling question please.
From: |
Pierre Gaston |
Subject: |
Re: [Help-bash] A string handling question please. |
Date: |
Tue, 24 Jul 2018 09:23:06 +0300 |
On Tue, Jul 24, 2018 at 9:19 AM, Pierre Gaston <address@hidden>
wrote:
>
>
> On Tue, Jul 24, 2018 at 3:10 AM, George R Goffe <address@hidden> wrote:
>
>> Hi,
>>
>> I'm writing a function that will build a string based on the args passed
>> to it and ultimately be executed as a bash command or commands linked via
>> pipes. I'm a little confused and need some help please.
>>
>> For example:
>>
>> invoke doit() with args a b c d e: doit $a $b $c $d $e
>>
>> generate command" xx=$(history | $a | $b | $c -z | $d | $e) and then
>> execute $xx.
>>
>> The history command produces nothing. Bash or maybe me is confused about
>> what's happening vs what I want to happen.
>>
>> Any hints/tips/suggestions/clues are welcome.
>>
>> Regards,
>>
>> George...
>>
>
> I'll make some assumptions as to what you want exactly, but maybe this
> will help:
>
> First, just to be sure the function must be defined in your current shell,
> so in a file you are sourcing, your .bashrc etc.. (see
> http://mywiki.wooledge.org/BashFAQ/060)
>
> Then I assume the variable contains commands that are correctly quoted, eg:
>
> a='grep -v "foo\$"'
> b='sed "s/^/b:"'
>
> a quick and simple way to check this is that if you type
>
> echo "$a"
>
> it should print a command that you can copy paste as is.
> (I suggest reading http://mywiki.wooledge.org/Quotes )
>
> Now, just expanding the commands will not be enough they will not be
> executed, you will need to evaluate them:
>
> doit () { eval xx="\$(history | "$1" | "$2")" ;}
>
> Note: the quotes are important here as well
>
> if you want something that takes a variable number of arguments:
> doit ()
> {
> local pipe arg;
> for arg in "$@";
> do
> pipe="$pipe | $arg";
> done;
> eval xx="\$(history ${pipe+"$pipe"})"
> }
>
> a='sed "s/^/filtered:/"'
> b="grep doit"
> doit "$a" "$b"
> echo "$xx"
>
I forgot to mention http://mywiki.wooledge.org/BashFAQ/048 about eval