Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pipes in an alias

I have this in my .bashrc:

alias jpsdir="jps | awk '{print $1}' | xargs pwdx"

but when I use jpsdir I get this output:

pwdx: invalid process id: JvmName

but running

jps | awk '{print $1}' | xargs pwdx

gives the correct results:

1234: /some/dir/

What is wrong with my alias? Should i make it a function ?

like image 402
dmc Avatar asked Feb 09 '23 02:02

dmc


1 Answers

As gniourf_gniourf has explained in the comments, the reason that your alias wasn't working was because the $1 in your awk command was being expanded by the shell. The value is likely to be empty, so the awk command becomes {print } and pwdx is being passed both parts of the output of jps.

You can avoid having to escape the $ by avoiding using awk entirely; you can use the -q switch rather than piping to awk:

jpsdir() {
    jps -q | xargs pwdx
}

I would personally prefer to use a function but you can use an alias if you like.

like image 69
Tom Fenech Avatar answered Feb 16 '23 10:02

Tom Fenech