简体   繁体   English

使用dot运行shell脚本为什么“echo $ 0”print -bash

[英]use dot to run a shell script why does “echo $0” print -bash

use dot to run a shell script why does "echo $0" print -bash 使用dot运行shell脚本为什么“echo $ 0”print -bash

Assuming I have a snippet of code below 假设我下面有一段代码

#!/usr/bin/env bash
echo $0

I execute using dot (.) 我用点(。)执行

. ./script.sh

Output: 输出:

-bash

However, 然而,

if i run without dot 如果我没有点运行

Output is the path name combined with the script name as I expected. 输出是路径名称与我期望的脚本名称相结合。

获取脚本在现有解释器中运行它而不是exec新脚本,这意味着$0未正常初始化。

When you run a script with . 使用时运行脚本. , it's essentially as if you typed the contents of the script directly on your shell command line. ,它基本上就像你直接在shell命令行上输入脚本的内容一样。 So echo "$0" will output exactly what it would output if you just typed it. 因此, echo "$0"将输出恰好输入的内容,如果您输入它。

The special variables like $0 are only initialized when you start up a new shell, which . $0这样的特殊变量只在你启动一个新shell时初始化. doesn't do, or else it wouldn't be very useful. 没有做,否则它不会很有用。

However, if you're using bash version 3 or greater, you can always find out what file is currently being executed thus: 但是,如果您使用的是bash版本3或更高版本,则始终可以找出当前正在执行的文件:

echo "$BASH_SOURCE"

which works no matter how the file is invoked. 无论文件如何被调用,它都有效。


. is an alias for source : source的别名:

Don't use this command for run a script, it has been created for import source files. 不要使用此命令来运行脚本,它是为导入源文件创建的。
You can see that here : Advanced Bash scripting guide 你可以在这里看到: 高级Bash脚本指南

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

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