【问题标题】:what does scripttorun=${0} do?scripttorun=${0} 是做什么的?
【发布时间】:2014-07-08 15:32:33
【问题描述】:

我正在浏览其他人编写的 shell 脚本。我可以在脚本开始时看到以下几行。我知道它必须与路径和所有东西有关。但是任何人都可以解释它是如何工作的吗?

#!/bin/ksh

scripttorun=${0}
scriptname=${0##/*/}
scriptname=$(basename $0)
scriptpath=${0%%/$scriptname}
if [ $scriptpath != $0 ];then
cd $scriptpath
fi

【问题讨论】:

标签: shell unix sh aix


【解决方案1】:

scripttorun=${0} 只是将$0 的内容赋值给scripttorun

您也可以使用(在这种情况下无需使用{...}):

scripttorun=$0

$0 是包含调用命令的脚本的第一个参数(例如:./script.sh)。

否则:

if [ $scriptpath != $0 ];then
cd $scriptpath
fi

当您使用test[ 时,您必须用双引号保护您的操作数。请参阅this reminder 了解更多详情。

所以你可以改用:

if [[ $scriptpath != $0 ]]; then
    cd "$scriptpath"
fi

# or

if [ "$scriptpath" != "$0" ]; then
    cd "$scriptpath"
fi

【讨论】:

    【解决方案2】:

    下面一行:

    scripttorun=${0}
    

    使用脚本的参数 #0 分配局部变量 $scripttorun。按照惯例,在 Unix 程序中,${0}(参数编号 0)始终是正在执行的脚本的调用路径。

    这个sn-p的作用,就是从当前脚本的路径中取出文件名,并将当前工作目录作为脚本所在的路径。

    【讨论】:

    • 所以意思是说从任何路径执行脚本,它将获取调用脚本所在的路径,然后如果从某个地方调用它,则会将目录更改为它?
    • 还有另一个变量他们在做什么 srciptname/
    猜你喜欢
    • 2011-05-04
    • 2015-12-06
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2023-01-21
    • 2017-06-03
    相关资源
    最近更新 更多