如何获取其中的目录路径的Bash脚本位于,里面那个脚本?
例如,假设我想使用Bash脚本作为另一个应用程序的启动器.我想将工作目录更改为Bash脚本所在的目录,因此我可以对该目录中的文件进行操作,如下所示:
$ ./application
当source用于从另一个脚本调用bash脚本时,我无法从该脚本中找出被调用脚本的名称.
file1.sh
#!/bin/bash
echo "from file1: $0"
source file2.sh
Run Code Online (Sandbox Code Playgroud)
file2.sh
#!/bin/bash
echo "from file2: $0"
Run Code Online (Sandbox Code Playgroud)
运行file1.sh
$ ./file1.sh
from file1: ./file1.sh # expected
from file2: ./file1.sh # was expecting ./file2.sh
Run Code Online (Sandbox Code Playgroud)
问:我怎样才能检索到file2.sh的file2.sh?
所以我想创建一个可移植的bashrc/bash_profile文件.我有一个单独的脚本,我象征性地链接到.bashrc,.bash_profile等.然后$0我看着根据调用的脚本切换我做的事情.问题是shell调用bashrc脚本当然它执行bash真的$0对我来说意味着什么-bash.$1更多未设置为脚本名称.
所以我的问题是,在bash中如何获取正在执行的脚本的名称.不是执行它的二进制文件,例如bash?
我认为它给了我-bash与$1未设置,因为这实在不是一个新的进程.有任何想法吗?
当我在运行Mac OS X v10.6.7(Snow Leopard)的Mac上的Bash脚本中引用$ 0时,我得到的不是脚本的名称.-bash
我运行了Stack Overflow问题中描述的脚本:
#!/bin/bash
echo
echo '# arguments called with ($@) --> '"$@"
echo '# $1 --------------------------> '"$1"
echo '# $2 --------------------------> '"$2"
echo '# path to me ($0) -------------> '"$0"
echo '# parent path (${0%/*}) -------> '"${0%/*}"
echo '# my name (${0##*/}) ----------> '"${0##*/}"
echo
Run Code Online (Sandbox Code Playgroud)
以下是:
> . show_parms.sh foo
# arguments called with ($@) --> foo
# $1 --------------------------> foo
# $2 -------------------------->
# path to …Run Code Online (Sandbox Code Playgroud) #!/bin/bash
if [ ! -f numbers ]; then echo 0 > numbers; fi
count=0
touch numbers
echo $count > numbers
while [[ $count != 100 ]]; do
if ln numbers numbers.lock
then
count=`expr $count + 1`
n=`tail -1 numbers`
expr $n + 1 >> numbers
rm numbers.lock
fi
done
Run Code Online (Sandbox Code Playgroud)
count=`expr $count + 1`我能做些什么来避免和 的竞争条件n=`tail -1 numbers`,这样当我同时运行两个脚本时,它只会达到 100,而不是 200。我研究了多个网站,但没有简洁的答案没有做一个巨大的功能。
我启动了script.sh,在里面我想知道他的名字是什么
是否有标准程序来了解脚本名称?我们的想法是能够从包含在其中的完整路径+名称中提取名称$0
谢谢