Быстрый доступ к рабочему каталогу фонового задания

sh -c "cd /tmp/sub_dir/pertinent_dir/../  \
&& zip -r pertinent_dir.zip pertinent_dir/*"
3
23.08.2016, 03:10
3 ответа

Если Ваше намерение состоит в том, чтобы получить рабочий каталог процесса, это - один путь:

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

Следующая функция внутри .bashrc, сделает точно, что Вы хотите

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

Пример:

~$ sleep 1h &
[1] 15102
~$ jobs
[1]+  Running                 sleep 1h &
~$ cd /
/$ cdjob %1
~$ 
5
27.01.2020, 21:11
  • 1
    Это помогает много в сочетании с jobs -p –  Bernhard 08.07.2013, 18:15

Можно сделать

cd /proc/$!/cwd

Или еще лучше:

cd -P /proc/$!/cwd

В первом случае pwd отобразит рабочий каталог как/proc/XXXXXX/cwd и pwd -P отобразит реальный путь к каталогу.

Второй метод изменится непосредственно на физический каталог, связанный с путем, который требуют.

2
27.01.2020, 21:11
  • 1
    Можно использовать cd -P вместо этого. –   08.07.2013, 18:33
  • 2
    Вы уверены, что это работает в ударе 3.2 согласно просьбе? –  Bernhard 08.07.2013, 18:35
  • 3
    @EvanTeitelman Awsome, Вы изучаете что-то enw каждый день. Обновленный. –  Johan 08.07.2013, 18:40
  • 4
    @Bernhard я подозреваю $! работы даже для очень старых версий удара, хотя CD-P является более новым дополнением. Я никогда не замечал это в пути прежде. Я не считал раздел о CD или pwd в странице справочника удара в течение многих лет. –  Johan 08.07.2013, 18:45
  • 5
    Просто подтвержденный путем рассмотрения источника. $! и cd -P работа с ударом 3.2. Я полагаю, что последний указан POSIX. –   08.07.2013, 18:59

Нет.

Я прошел SHELL BUILTIN COMMANDS раздел bash(1) страница справочника и не могла найти, что функция изменилась на текущий рабочий каталог фонового задания.

$ 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 ...]

Править: Я неправильно понял Ваш вопрос. Я думал, что Вы искали единственную встроенную команду для выполнения этого действия.

1
27.01.2020, 21:11

Теги

Похожие вопросы