linux - cd && ls | grep: How to execute a command in the current shell and pass the output -
i created alias in order not write ls every time move new directory:
alias cl='cd_(){ cd "$@" && ls; }; cd_'
let have folder named "downloads" (which of course happen have) type following in terminal:
cl downloads
now find myself in "downloads" folder , receive list of stuff have in folder, say: example.txt, hack.hs, picture.jpg,...
if want move directory , if there is, say, hack.hs try this:
cl downloads | grep hack
what output:
hack.hs
but remain in folder (which means not in downloads).
i understand happens because every command executed in subshell, , cd downloads && ls executed in subshell of own , output (namely list of stuff have) gets redirected via pipe grep. why not in new folder.
my question following:
how do in order able write "cl downloads | grep hack" , "hack"-greped list of stuff , in downloads folder?
thank much, pol
for ever googling this: quick fix proposed @gniourf_gniourf :
cl downloads > >(grep hack)
some marked question possible duplicate of make bash alias takes duplicates, fact bash alias takes arguments shows not case. problem @ hand how execute command in current shell while @ same time redirecting output command.
as you're aware (and covered in bashfaq #24), reason
{ cd "$@" && ls; } | grep ...
...prevents results of cd
being visible in outer shell no component of pipeline guaranteed posix run in outer shell. (some shells, including ksh [out-of-the-box] , modern bash non-default options enabled, or optionally run last piece of pipeline in parent shell, can't portably relied on).
a way avoid this, that's applicable posix shells, direct output named pipe, avoiding setting pipeline:
mkfifo mypipe grep ... <mypipe & { cd "$@" && ls; } >mypipe
in modern ksh , bash, there's shorter syntax -- using /dev/fd
entries instead of setting named pipe if operating system provides facility:
{ cd "$@" && ls; } > >(grep ...)
in case, >(grep ...)
replaced filename points either fifo or /dev/fd
entry that, when written process in question, redirects output grep
-- without pipeline.
by way -- hope use of ls
in manner example. output of ls
not well-specified range of possible filenames, grepping innately unreliable. consider using printf '%s\0' *
emit nul-delimited list of non-hidden names in directory, if want build streamed result; or using glob expressions check files matching specific pattern (bashfaq #4 covers similar scenario); extglobs available if need closer full regex matching support posix patterns support.
Comments
Post a Comment