Search code examples
bashfindlsxargs

How to avoid `ls .` when `find | xargs ls` has no result?


me@new840:~/.config$ ls -al 
total 196
drwx------ 40 me me 4096 Aug 22 22:08  .
drwxr-xr-x 52 me me 4096 Aug 22 12:12  ..
drwxr-xr-x  2 me me 4096 Jul 23 04:36  autostart
drwxr-xr-x  2 me me 4096 Jul 25 00:30  bcompare
drwx------ 20 me me 4096 Aug 22 22:37  Code
drwx------  2 me me 4096 Aug 22 22:50  dconf
drwxr-xr-x  3 me me 4096 Aug 15 07:19  deadbeef
-rw-------  1 me me 1131 Nov 21  2016  dleyna-server-service.conf

me@new840:~/.config$ find /home/me/.config ! -user "me" -type f -print0 | xargs -0 ls -Al
total 188
drwxr-xr-x  2 me me 4096 Jul 23 04:36  autostart
drwxr-xr-x  2 me me 4096 Jul 25 00:30  bcompare
drwx------ 20 me me 4096 Aug 22 22:37  Code
drwx------  2 me me 4096 Aug 22 22:56  dconf
drwxr-xr-x  3 me me 4096 Aug 15 07:19  deadbeef
-rw-------  1 me me 1131 Nov 21  2016  dleyna-server-service.conf

Actually,the result of find /home/me/.config ! -user "me" -type f -print0 | xargs -0 ls -Al should be empty.

How to avoid ls . when find | xargs ls has no result?


Solution

  • GNU xargs has the -r option to avoid doing anything if it receives no input, but this is not portable.

    With find, the solution is simple: use -exec instead of xargs.

    
    find /home/me/.config ! -user "me" -type f -exec ls -Al {} +
    

    Tangentially, don't use ls in scripts.