Acesso rápido ao diretório de trabalho do job em background

3

Um esforço mínimo para reproduzir o que estou procurando é o seguinte

/$ sleep 1h &
[1] 6564
/$ cd
~$ jobs
[1]+  Running                 sleep 1h &  (wd: /)

Quando uso jobs para gerenciar meus processos em segundo plano, o diretório de trabalho (wd) também é exibido quando é diferente do diretório atual.

Existe uma maneira fácil de mudar facilmente para este diretório de trabalho exibido? Estou usando o bash 3.2.

Eu não estou procurando por funções de wrapper usando awk ou ferramentas similares, estou especificamente procurando por um shell construído em solução.

    
por Bernhard 08.07.2013 / 16:06

3 respostas

5

Se sua intenção é obter o diretório de trabalho de um processo, essa é uma maneira:

~ » jobs -l
[1]  + 14308 running    sleep 1h
~ » readlink /proc/14308/cwd
/home/matti-nillu

A seguinte função dentro de .bashrc , fará exatamente o que você quer

cdjob () 
{ 
    pid=$(jobs -p $1);
    d=$(readlink /proc/$pid/cwd);
    cd "$d"
}

Exemplo:

~$ sleep 1h &
[1] 15102
~$ jobs
[1]+  Running                 sleep 1h &
~$ cd /
/$ cdjob %1
~$ 
    
por 08.07.2013 / 17:03
2

Você pode fazer

cd /proc/$!/cwd

Ou melhor ainda:

cd -P /proc/$!/cwd

No primeiro caso, pwd exibirá o diretório de trabalho como / proc / XXXXXX / cwd e pwd -P exibirá o caminho real do diretório.

O segundo método será alterado diretamente para o diretório físico vinculado ao caminho solicitado.

    
por 08.07.2013 / 17:26
1

Não há.

Passei pela seção SHELL BUILTIN COMMANDS da página bash(1) e não consegui encontrar um recurso para alterar para o diretório de trabalho atual de um trabalho em segundo plano.

$ head -n3 shell-builtin-commands
SHELL BUILTIN COMMANDS
   Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to sig‐
   nify the end of the options.  The :, true, false, and test builtins do not accept options and do not treat -- specially.  The
$ grep change bash-shell-builtin-commands
           rent  directory  is  searched  if  no file is found in PATH.  If the sourcepath option to the shopt builtin command is
           turned off, the PATH is not searched.  If any arguments are supplied, they become the positional parameters when file‐
           name  is  executed.   Otherwise  the positional parameters are un**changed**.  The return status is the status of the last
           command exited within the script (0 if no commands are executed), and false if filename is  not  found  or  cannot  be
           read.
--
                  Cause  shell-command to be executed whenever keyseq is entered.  When shell-command is executed, the shell sets
                  the READLINE_LINE variable to the contents of the readline line buffer and the READLINE_POINT variable  to  the
                  current  location  of the insertion point.  If the executed command **changes** the value of READLINE_LINE or READ‐
                  LINE_POINT, those new values will be reflected in the editing state.

--
           (see also the -P option to the set builtin command); the -L option forces symbolic links to be followed.   If  the  -e
           option  is  supplied  with  -P, and the current working directory cannot be successfully determined after a successful
           directory **change**, cd will return an unsuccessful status.  An argument of - is equivalent to $OLDPWD.  If  a  non-empty
           directory  name  from CDPATH is used, or if - is the first argument, and the directory **change** is successful, the abso‐
           lute pathname of the new working directory is written to the standard output.  The return value is true if the  direc‐
           tory was successfully **changed**; false otherwise.

    command [-pVv] command [arg ...]
--
           The first form lists the active jobs.  The options have the following meanings:
           -l     List process IDs in addition to the normal information.
           -n     Display information only about jobs that have **changed** status since the user was last notified of their status.
           -p     List only the process ID of the job's process group leader.
           -r     Restrict output to running jobs.
--
           Removes entries from the directory stack.  With no arguments, removes the top directory from the stack, and performs a
           cd to the new top directory.  Arguments, if supplied, have the following meanings:
           -n     Suppresses  the  normal **change** of directory when removing directories from the stack, so that only the stack is
                  manipulated.
           +n     Removes the nth entry counting from the left of the list shown by  dirs,  starting  with  zero.   For  example:
--
           If the popd command is successful, a dirs is performed as well, and the return status is 0.  popd returns false if  an
           invalid option is encountered, the directory stack is empty, a non-existent directory stack entry is specified, or the
           directory **change** fails.

    printf [-v var] format [arguments]
--
    pushd [-n] [dir]
           Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the  current
           working  directory.  With no arguments, ex**changes** the top two directories and returns 0, unless the directory stack is
           empty.  Arguments, if supplied, have the following meanings:
           -n     Suppresses the normal **change** of directory when adding directories to the stack,  so  that  only  the  stack  is
                  manipulated.
           +n     Rotates  the  stack  so that the nth directory (counting from the left of the list shown by dirs, starting with
--
           If  the  pushd  command is successful, a dirs is performed as well.  If the first form is used, pushd returns 0 unless
           the cd to dir fails.  With the second form, pushd returns 0 unless the directory stack is empty, a non-existent direc‐
           tory stack element is specified, or the directory **change** to the specified new current directory fails.

    pwd [-LP]
--

    readonly [-aAf] [-p] [name[=word] ...]
           The given names are marked readonly; the values of these names may not be **changed** by subsequent assignment.  If the -f
           option  is supplied, the functions corresponding to the names are so marked.  The -a option restricts the variables to
           indexed arrays; the -A option restricts the variables to associative arrays.  If both options are supplied,  -A  takes
--
                   subshell environment.  The ERR trap is normally not inherited in such cases.
           -H      Enable !  style history substitution.  This option is on by default when the shell is interactive.
           -P      If  set,  the  shell does not follow symbolic links when executing commands such as cd that **change** the current
                   working directory.  It uses the physical directory structure instead.  By default, bash  follows  the  logical
                   chain of directories when performing commands which **change** the current directory.
           -T      If  set,  any  traps on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands
                   executed in a subshell environment.  The DEBUG and RETURN traps are normally not inherited in such cases.
--
                   parameters are set to the args, even if some of them begin with a -.
           -       Signal  the  end of options, cause all remaining args to be assigned to the positional parameters.  The -x and
                   -v options are turned off.  If there are no args, the positional parameters remain unchanged**.

           The options are off by default unless otherwise noted.  Using + rather than - causes these options to be  turned  off.
--
    shift [n]
           The positional parameters from n+1 ... are renamed to $1 ....  Parameters represented by the numbers $# down to $#-n+1
           are  unset.  n must be a non-negative number less than or equal to $#.  If n is 0, no parameters are **changed**.  If n is
           not given, it is assumed to be 1.  If n is greater than $#, the positional parameters are  not  **changed**.   The  return
           status is greater than zero if n is greater than $# or less than zero; otherwise 0.

--
           cdable_vars
                   If set, an argument to the cd builtin command that is not a directory is assumed to be the name of a  variable
                   whose value is the directory to **change** to.
           cdspell If  set,  minor errors in the spelling of a directory component in a cd command will be corrected.  The errors
                   checked for are transposed characters, a missing character, and one character too many.  If  a  correction  is
--
                   easy re-editing of multi-line commands.
           compat31
                   If  set,  bash  **changes**  its behavior to that of version 3.1 with respect to quoted arguments to the [[ condi‐
                   tional command's =~ operator.
           compat32
                   If set, bash **changes** its behavior to that of version 3.2 with respect  to  locale-specific  string  comparison
                   when  using  the [[ conditional command's < and > operators.  Bash versions prior to bash-4.1 use ASCII colla‐
                   tion and strcmp(3); bash-4.1 and later use the current locale's collation sequence and strcoll(3).
           compat40
                   If set, bash **changes** its behavior to that of version 4.0 with respect  to  locale-specific  string  comparison
                   when using the [[ conditional command's < and > operators (see previous item) and the effect of interrupting a
                   command list.
--
           direxpand
                   If  set, bash replaces directory names with the results of word expansion when performing filename completion.
                   This **changes** the contents of the readline editing buffer.  If not set, bash attempts to preserve what the user
                   typed.
           dirspell
--
           login_shell
                   The  shell  sets  this  option if it is started as a login shell (see INVOCATION above).  The value may not be
                   changed**.
           mailwarn
                   If set, and a file that bash is checking for mail has been accessed since the last time it  was  checked,  the
--
           restricted_shell
                   The  shell  sets  this option if it is started in restricted mode (see RESTRICTED SHELL below).  The value may
                   not be **changed**.  This is not reset when the startup files are executed, allowing the startup files to discover
                   whether or not a shell is restricted.
           shift_verbose
--
           value  of the mask is printed.  The -S option causes the mask to be printed in symbolic form; the default output is an
           octal number.  If the -p option is supplied, and mode is omitted, the output is in a form that may be reused as input.
           The return status is 0 if the mode was successfully **changed** or if no mode argument was supplied, and false otherwise.

    unalias [-a] [name ...]

Editar: Eu não entendi sua pergunta. Eu pensei que você estava procurando por um único comando interno para executar essa ação.

    
por 08.07.2013 / 16:22