简体   繁体   English

如何使脚本独立于执行位置

[英]How to make script independent from where it is executed

I am running into the problem of commands failing because I expect them to be executed at some directory and that is not the case. 我遇到了命令失败的问题,因为我希望它们在某个目录中执行,而事实并非如此。

For example I want to do: 例如,我想做:

pdfcrop --margins '0 0 -390 0' $pag "$pag"_1stCol.pdf

to create a new pdf document, and then 创建一个新的pdf文档,然后

mv `\ls /home/dir | grep '_1stCol'` /home/gmanglano/dir/columns

The problem is that the mv command is failing because it finds the document, it is trying to move that file found FROM the directory where I executed the script, not from where it was found. 问题是mv命令失败,因为它找到了文档,它试图将找到的文件从执行脚本的目录而不是从找到脚本的目录中移出。

This is happening to me somewhat often and I feel there is a concept I am missing or I am thinking this the wrong way arround. 这在我身上经常发生,我觉得我缺少一个概念,或者我认为这是错误的方法。

The error I get is: 我得到的错误是:

mv: cannot stat '1stCol.pdf': No such file or directory

When there is, in fact, said fail, it just is not in the directory I launched the script. 实际上,当说失败时,它只是不在我启动脚本的目录中。

Instead of monkeying with ls and backticks and all that, just use the find command. 与其烦恼ls和反引号等等,不如使用find命令。 It's built for to find files and then execute a command based on the results of that find: 它用于查找文件,然后根据查找结果执行命令:

 find /home/dir -name "*_1stCol.pdf" -exec mv {} /home/gmanglano/dir/columns \;

This is finding files in /home/dir that match the name *_1stCol.pdf and then moves them. 这是在/home/dir中找到与名称*_1stCol.pdf匹配的*_1stCol.pdf ,然后将其移动。 The {} is the token for the found file. {}是找到的文件的标记。

Don't parse the output of ls : if you simplify the mv command to 不要解析ls的输出 :如果将mv命令简化为

mv /home/dir/*_1stCol.pdf /home/gmanglano/dir/columns

then you won't have an issue with being in the wrong directory. 这样就不会出现在错误目录中的问题。

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

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