如何在Linux的当前Shell中执行脚本? [英] How to execute script in the current shell on Linux?

查看:159
本文介绍了如何在Linux的当前Shell中执行脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从whitin标记要在当前shell中执行的脚本? 我知道我可以使用:

Is there a way to mark a script to be executed in the current shell from whitin It? I know I can use:

. ./path/myscript.sh

但是我需要一种在脚本中包含点"方式的方法.

but I need a way to include the "dot" way inside the script.

就是这种情况.我在目录A中有一个脚本"myscript.sh":

Here is the case. I have a script "myscript.sh" located in directory A:

rm -r A
mkdir A
touch A/test.file
cd A

以正常方式执行脚本时:

When the script is executed in normal a way:

sh myscript.sh

退出脚本时,我无法列出目录. 在当前shell中启动脚本时:

When exiting the script I cannot list the directory. When script is started in the current shell:

. ./myscript.sh

没有问题.我需要一种在脚本中包含这种点"方式的方法,这样就可以在没有It的情况下调用它.

There is no problem. I need a way to include this "dot" way inside my script so It can be called without It.

推荐答案

在shell中执行脚本有两种方法.根据您的需要,您将需要执行以下一项操作(不要同时执行!).

There are two ways of executing a script in the shell. Depending upon your needs, you will have to do one of the following (don't do both!).

  1. 将脚本作为程序启动,在该程序中有自己的进程.
  2. 将脚本作为一堆文本来提供,该文本由当前的shell处理.

要将脚本作为程序启动:

To launch the script as a program:

  • 将行#!/bin/bash添加为脚本的第一行
  • Add the line #!/bin/bash as the first line of the script

这将由加载程序读取,加载程序具有特殊的逻辑,该逻辑将前两个字符#!插入为启动下一个程序并将其内容传递给它".请注意,这仅适用于为接收内容而编写的程序

This will be read by the loader, which has special logic that interperts the first two characters #! as "launch the program coming next, and pass the contents into it". Note this only properly works for programs written to receive the contents

要将脚本源到当前shell中:

To source the script into the current shell:

  • 键入命令. script.shsource script.sh

注意:bash中的.等同于bash中的source.

Note: . in bash is equivalent to source in bash.

这就像您键入"script.sh"的内容一样.例如,如果您在"script.sh"中设置变量,则该变量将在当前shell中设置.您将需要取消定义变量以将其从当前shell中清除.

This acts as if you typed in the contents of "script.sh". For example, if you set a variable in "script.sh" then that variable will be set in the current shell. You will need to undefine the variable to clear it from the current shell.

这与#!/bin/bash示例有很大的不同,因为在新的bash子进程中设置变量不会影响您从中启动该子进程的shell.

This differs heavily from the #!/bin/bash example, because setting a variable in the new bash subprocess won't impact the shell you launched the subprocess from.

这篇关于如何在Linux的当前Shell中执行脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆