简体   繁体   English

在shell脚本中包含一大块代码

[英]Including a chunk of code in a shell script

I have a number of shell scripts that all look like this: 我有许多shell脚本,看起来像这样:

#!/bin/bash

cd ~/Dropbox/cms_sites/examplesite/media
sass -C --style compressed --update css:css

cd ~/Dropbox/cms_sites/examplesite

rm -f ./cache/*.html
rm -fr ./media/.sass-cache/
rm -fr ./admin/media/.sass-cache/


rsync -auvzhL . username@host:/home/username/remote_folder

(I know the use of cd seems weird, but they have evolved!) (我知道cd的使用看起来很奇怪,但它们已经发展了!)

Now, all these scripts have a few differences, in that they have different usernames, hosts, local folder and remote folder names, and I want an inexperienced user to be able to run them without arguments (so he can drag and drop them into a terminal without issue). 现在,所有这些脚本都有一些区别,因为它们有不同的用户名,主机,本地文件夹和远程文件夹名称,我希望没有经验的用户能够在没有参数的情况下运行它们(因此他可以将它们拖放到一个终端没有问题)。

What I'd like to do is something like: 我想做的是:

#!/bin/bash

cd ~/Dropbox/cms_sites/examplesite/media
sass -C --style compressed --update css:css

cd ~/Dropbox/cms_sites/examplesite

include ~/scripts/common.sh

rsync -auvzhL . username@host:/home/username/remote_folder

then have a file in common.sh that looks like: 然后在common.sh中有一个文件,如下所示:

rm -f ./cache/*.html
rm -fr ./media/.sass-cache/
rm -fr ./admin/media/.sass-cache/

so that I can easily change sections of the code in lots of scripts at once. 这样我就可以轻松地一次更改许多脚本中的代码部分。

Is this possible, or is there a better way to do this without using arguments and having one script? 这是可能的,还是有更好的方法来做到这一点,而不使用参数和一个脚本?

Use the source command. 使用source命令。 It's bash's version of 'include' 这是bash的'include'版本

No need for "include" if the script is executable: 如果脚本是可执行的,则不需要“include”:

~/scripts/common.sh

If the script is not executable or does not have an appropriate shebang line then you'll need to specify the interpreter: 如果脚本不可执行或没有适当的shebang行,那么您需要指定解释器:

bash ~/scripts/common.sh

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

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