Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I wanted to write a function to retrieve a field from the list of background jobs in bash. For example to get a specific argument.

Let's say I send vim to the background, so "jobs" displays this list:

[1]+  Stopped                 vim ~/.bashrc

My function looks like this:

function jf {
    echo `jobs | awk 'NR==$1{print $$2}'`;
}

I then call it like this:

jf 1 4

I would want it to return the 4th column of the 1st line, which would be "~/.bashrc", but it doesn't. What Am I doing wrong?

share|improve this question
    
Too many $s: awk 'NR==1{print $4}'. –  manatwork Apr 10 '13 at 14:20
    
I need the $ to refer to the respective arguments. The function is supposed to receive the line number as first, and the column number as the second argument. –  bug Apr 10 '13 at 14:27
    
$1, $2 and alike are not command line arguments in awk, but fields of the current record. –  manatwork Apr 10 '13 at 14:37
    
I know, but shouldn't bash substitute the arguments with their values before it executes awk? So that $1 becomes 1 and $2 becomes 4 in my example. I mean, that's the point of using the dollar sign in a bash function, isn't it? –  bug Apr 10 '13 at 15:26
1  
Not inside single quoted strings. awk "NR==$1{print \$$2}" –  manatwork Apr 10 '13 at 15:44

2 Answers 2

You need to tell awk that you want to pass in values from shell variables. Something like this in your function definition should do the trick:

function jf {
    echo `jobs | awk -v LINENO=$1 -v COLUMNNO=$2 'NR==LINENO {print $COLUMNNO}'`
}
share|improve this answer
    
Thanks, this seems to work great! The solution hinted at by manatwork is more general though. –  bug Apr 10 '13 at 17:12

The single quotes made bash not substitute arguments. As manatwork mentioned, double quotes are interpreted less strictly.

manatwork wrote:

awk "NR==$1{print \$$2}"

Still, the "echo `...`" part in my function posed a problem, but it seems I overcomplicated things and it isn't needed at all. This new function works for me:

function jf {
    jobs | awk "NR==$1{print \$$2}";
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.