简体   繁体   English

这是在外壳程序脚本中使用cd和cd-命令在另一个目录中进行某些计算的好方法吗

[英]Is it a good way to use cd and cd - commands in a shell script for some computation in another directory

I use cd in my shell script to enter into a directory for some computation and again use cd - to come back. 我在外壳程序脚本中使用cd进入目录进行一些计算,然后再次使用cd-返回。 Is it a good way to use? 这是一个好方法吗? My script is: 我的脚本是:

input_dir=/home/abc/2001/01/
cd $input_dir
#Execute some programm with ifile.txt e.g.
awk '$1 > 99 {printf "%.2f" "$1"}' ifile.txt > ofile.tx 
cd -

or we should always mention the path name? 还是我们应该经常提及路径名? like: 喜欢:

input_dir=/home/abc/2001/01/
awk '$1 > 99 {printf "%.2f" "$1"}' $input_dir/ifile.txt > $input_dir/ofile.txt

Can you please suggest if there is anything easy way to reduce the texts? 您能否建议是否有任何简便的方法来减少文本?

Put it in a subshell: 把它放在一个子shell中:

(cd "$input_dir" && exec awk '$1 > 99 {printf "%.2f" "$1"}' ifile.txt > ofile.tx)

Thus, when the subshell exits, you're automatically back to your original directory, because the cd only applied to that subshell (containing only the awk command). 因此,当子shell退出时,您将自动返回到原始目录,因为cd仅应用于该子shell(仅包含awk命令)。

The exec ensures that you're not incurring extra overhead, as it causes the subshell to replace its process table entry with the awk . exec确保您不会招致额外的开销,因为它会导致子外壳将其进程表条目替换为awk (Some shells will do this automatically for the last command inside a subshell). (某些外壳程序会自动对子外壳程序中的最后一个命令执行此操作)。

A common technique to limit the scope of cd for a given computation is to run the command in a subshell, like this: 限制cd用于给定计算的范围的常用技术是在子shell中运行命令,如下所示:

(cd "${inputdir}" && awk '…')

This is however not always applicable, because the subshell has limited ways to to communicate with the parent shell. 但是,这并不总是适用的,因为子外壳与父外壳进行通信的方式有限。 The subshell introduce a frontier confining manipulations involving the following resources: 该子外壳介绍了涉及以下资源的边界限制操作:

  • job control 工作控制
  • variables 变量
  • of SIGNAL handlers SIGNAL处理程序

If you need the computation occurring in the directory to interact with these resources of the parent script , you still can still delimit the scope of the cd with a subshell provided that you: 如果您需要在目录中进行计算以与父脚本的这些资源进行交互,则仍然可以使用子外壳来划定cd的范围,前提是您:

  • either use a named FIFO to let the child notify required job control, variables, signal manipulation to the parent script 要么使用命名的FIFO来让子级将所需的作业控制,变量,信号操作通知给父级脚本

  • or rewrite the computation so that only input and simple processing occur in the subshell, while the parent shell reads and interpret the results through an anonymous pipe. 或重写计算,以便子外壳中仅发生输入和简单处理,而父外壳通过匿名管道读取和解释结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM