Saturday, March 12, 2022

[SOLVED] Using pipes in an alias

Issue

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 ?


Solution

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.



Answered By - Tom Fenech
Answer Checked By - Candace Johnson (WPSolving Volunteer)