0

I want to make a bash alias of the following command, which works typed out on the command line but all my attempts at making an alias have failed. My only diagnosis is that all those nested quotes and the loop are scary and I don't know how to handle them.

sudo ss -x src "*/tmp/.X11-unix/*" | grep -Eo "[0-9]+\s*$" | while read port
do sudo ss -p -x | grep -w $port | grep -v X11-unix 
done | grep -Eo '".+"' | sort | uniq -c | sort -rn

Is it possible to alias this command?

1
  • Why don't you use a function? As an alias you just need to call the name of this one Commented May 23, 2022 at 4:10

1 Answer 1

1

For anything more complicated than, say, adding an option to some command, use shell functions rather than aliases.

Here's a function, mything, that you would define in the same place where you would ordinarily define aliases, which runs the command s that you show:

mything () {
    sudo ss -x src "*/tmp/.X11-unix/*" |
    grep -Eo "[0-9]+\s*$" |
    while read -r port; do
        sudo ss -p -x | grep -w "$port"
    done |
    grep -v X11-unix | grep -Eo '".+"' |
    sort | uniq -c | sort -rn
}

I haven't looked closer to the actual commands that you are running (apart from fixing the unquoted use of $port and moving one grep out of the loop), but it seems like at least some of the operations may be replaceable by awk and you should be able to remove that loop or at least move sudo ss out of it. The main thing is that if you have something even remotely complicated to run, create a shell function for it.

1
  • Making it a script even would then make that command available outside of interactive shells (and also means you could use a language / shell more capable than bash to write it). Functions are only necessary if we need to modify the internal state of the shell. Commented May 23, 2022 at 6:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .