脚本的全名和路径$ 0不可见调用时 [英] script full name and path $0 not visible when called
问题描述
我有一个剧本task.sh具有以下内容:
I have a script "task.sh" with the following content:
#!/bin/bash
CUR_DIR=`pwd`
SCRIPTPATH="${CUR_DIR}/`dirname $0`"
当我把它与庆典task.sh它工作正常,但是当它被称为用。task.sh
when I call it with "bash task.sh" it works as expected but when it is called with ". task.sh"
$ . log/task.sh
dirname: invalid option -- b
Try `dirname --help' for more information.
当该脚本被安排在crontab中它不工作为好。
谁能告诉我什么我做错了,或以不同的方式,以获得一个脚本的目录不是当前目录
?
When the script is being scheduled in crontab it is not working as well. Can someone tell me what am I doing wrong or a different way in order to get the directory of a script that is not the current directory ?
推荐答案
当你调用它作为庆典task.sh
,庆典分配task.sh$ 0(从 bash的手动:如果bash命令文件[引用...] $ 0被设置到该文件的名称。)。
When you invoke it as bash task.sh
, bash assigns "task.sh" to $0 (from the bash manual: "If Bash is invoked with a file of commands [...] $0 is set to the name of that file.").
在源文件时,bash不会改变$ 0,则只是执行在当前环境中的脚本。在当前的环境是什么在$ 0里?
When you source the file, bash does not alter $0, it just executes the script in the current environment. What's in $0 in your current enviroment?
$ echo "$0"
-bash
领先的破折号将是目录名
PTED作为一个选项间$ P $。
The leading dash will be interpreted by dirname
as an option.
如果它在cron作业,你为什么采购呢?
If it's in a cron job, why are you sourcing it?
如果你需要源脚本,这会如果你的shell是bash工作:
If you need to source your script, this will work if your shell is bash:
SCRIPTPATH="${CUR_DIR}/${BASH_ARGV[0]}"
然而,cron的壳是,我相信,/ bin / sh的。即使/ bin / sh的是一个符号链接的bash,当bash是作为SH它将尝试表现POSIXly:在BASH_ARGV阵列可能不会提供给您
However, cron's shell is, I believe, /bin/sh. Even if /bin/sh is a symlink to bash, when bash is invoked as sh it will try to behave POSIXly: the BASH_ARGV array probably won't be available to you.
这篇关于脚本的全名和路径$ 0不可见调用时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!